简体   繁体   English

重定向到索引后验证表单数据(而不是显示)

[英]Validate Form Data After Redirect to Index (Instead of Show)

In Rails, I'm attempting to validate form data and if valid, redirect to the index page for that class instead of it's show page. 在Rails中,我尝试验证表单数据,如果有效,请重定向到该类的索引页面,而不是显示页面。 I've set this up as follows: 我将其设置如下:

In the model: 在模型中:

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

In the controller: 在控制器中:

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

The problem I'm having is that while the validation does prevent the product from being made, it still redirects to the index page instead of displaying the errors on the new page. 我遇到的问题是,虽然验证确实阻止了产品的生产,但它仍然重定向到索引页面,而不是在新页面上显示错误。 I'm guessing I need to add an if statement to the controller to only render index if the form is valid, but I'm not sure what that statement would look like. 我猜想我需要向控制器添加一个if语句,以便仅在表单有效时才呈现索引,但是我不确定该语句的外观。

Your create action should look like: 您的create动作应类似于:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM