【问题标题】:Validate Form Data After Redirect to Index (Instead of Show)重定向到索引后验证表单数据(而不是显示)
【发布时间】:2014-11-06 16:50:40
【问题描述】:

在 Rails 中,我正在尝试验证表单数据,如果有效,则重定向到该类的索引页面,而不是显示页面。我设置如下:

在模型中:

validates :name, :description, :link, presence:true

在控制器中:

def new
  @product = Product.new
  respond_with(@product)
end

def create
  @product = Product.new(product_params)
  @product.save
  @products = Product.all
  render action: "index"
end

我遇到的问题是,虽然验证确实阻止了产品的制造,但它仍然重定向到索引页面,而不是在新页面上显示错误。我猜我需要向控制器添加一个 if 语句,以便仅在表单有效时才呈现索引,但我不确定该语句会是什么样子。

【问题讨论】:

    标签: ruby-on-rails validation


    【解决方案1】:

    您的create 操作应如下所示:

    def create
      @product = Product.new(product_params)
      if @product.save
        @products = Product.all
        render action: "index"
      else
        render action: "new"
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 2020-05-24
      相关资源
      最近更新 更多