Ruby on rails RubyonRails5-Resource在检查它是否已经存在时给出了错误信息——不管它是否存在
我正在尝试检查一个产品是否已经存在——如果已经存在,就会出现一条闪光消息,并带有指向已经存在的产品的链接。如果没有,则应创建产品 问题在于,无论产品是否已经存在,闪存错误都会出现。我哪里做错了 products_controller.rb:Ruby on rails RubyonRails5-Resource在检查它是否已经存在时给出了错误信息——不管它是否存在,ruby-on-rails,ruby,ruby-on-rails-5,Ruby On Rails,Ruby,Ruby On Rails 5,我正在尝试检查一个产品是否已经存在——如果已经存在,就会出现一条闪光消息,并带有指向已经存在的产品的链接。如果没有,则应创建产品 问题在于,无论产品是否已经存在,闪存错误都会出现。我哪里做错了 products_controller.rb: def create @product = Product.new(product_params) if @product.product_code.present? @existing_product = Product.
def create
@product = Product.new(product_params)
if @product.product_code.present?
@existing_product = Product.where(product_code: "#{@product.product_code}").ids.first.to_s
flash.now[:error] = %Q[This product already exists: <a href="/products/#{@existing_product}">#{@product.product_code}</a>. Please either rename this product or view/edit the existing one.].html_safe
render 'new'
elsif @product.save
redirect_to @product
else
render 'new'
end
end
1234是我正在尝试的产品代码。您的条件检查错误。这:
if @product.product_code.present?
仅检查您刚制作的@product
中是否存在product\u code
,而不检查数据库中是否存在与该产品代码相关的内容
我想你想要更像这样的东西:
@existing_product = Product.find_by(product_code: @product.product_code)
if @existing_product
flash.now[:error] = ...
render 'new'
elsif @product.save
redirect_to @product
else
render 'new'
end
您可以使用find_by
来查找您正在寻找的东西,这将为您提供产品或nil
(如果没有匹配的产品)
您可能还需要研究其他几件事情:
@现有的\u产品
,然后将链接和您需要的任何“复杂”错误消息完全放在视图中你的条件是检查错误的东西。这:
if @product.product_code.present?
仅检查您刚制作的@product
中是否存在product\u code
,而不检查数据库中是否存在与该产品代码相关的内容
我想你想要更像这样的东西:
@existing_product = Product.find_by(product_code: @product.product_code)
if @existing_product
flash.now[:error] = ...
render 'new'
elsif @product.save
redirect_to @product
else
render 'new'
end
您可以使用find_by
来查找您正在寻找的东西,这将为您提供产品或nil
(如果没有匹配的产品)
您可能还需要研究其他几件事情:
@现有的\u产品
,然后将链接和您需要的任何“复杂”错误消息完全放在视图中非常感谢,效果很好。我只需要确保链接指向现有产品的id,但在其他方面效果很好。一直在尝试使用URL帮助程序,但无法使其脱离html。我会继续努力!您不应该在flash消息中添加HTML,最好使用实例变量并在视图中使用该变量,例如使用
@existing\u product
,如果这种情况非常感谢,那么效果非常好。我只需要确保链接指向现有产品的id,但在其他方面效果很好。一直在尝试使用URL帮助程序,但无法使其脱离html。我会继续努力!您不应该将HTML放入flash消息中,最好使用实例变量并在视图中使用该变量,例如,在这种情况下,使用@existing\u product