Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在rails中显示关联所需的表单字段?_Ruby On Rails_Validation - Fatal编程技术网

Ruby on rails 如何在rails中显示关联所需的表单字段?

Ruby on rails 如何在rails中显示关联所需的表单字段?,ruby-on-rails,validation,Ruby On Rails,Validation,我是rails新手,我不知道如何设置组合框以便在浏览器中显示为“必需”。我有一个产品和一个位置,并且在产品中需要位置: class Product < ApplicationRecord belongs_to :location validates :location, presence: true end class Location < ApplicationRecord has_many :products end “show\u标签帮助程序正确地看到需要:lo

我是rails新手,我不知道如何设置组合框以便在浏览器中显示为“必需”。我有一个
产品
和一个
位置
,并且在产品中需要位置:

class Product < ApplicationRecord
  belongs_to :location
  validates :location, presence: true
end

class Location < ApplicationRecord
  has_many :products
end
show\u标签
帮助程序正确地看到需要
:location
,但是模型本身在表单发布后无法验证,因为此处的location是字符串(位置的:id),而不是实际的
位置
。”

当我改用
:location\u id

<%= f.collection_select :location_id, @locations, :id, :name, include_blank: true %>

然后,
show\u label
没有看到
:location\u id
是必需的属性,因此我没有获得必需的字段注释,但在保存模型时位置会正确保存


呈现组合框的正确方法是什么,这样我既可以识别它是否是必填字段,又可以允许我的控制器保存我的产品?我觉得我可能错过了一些人们都知道的东西。

尝试使用
验证:location\u id,presence:true
。它与其他验证不同(您可以设置一个不存在的id,它将是有效的,因为它存在,但它将是一个无效的位置),因此也保留
:location
验证。

尝试使用
验证:location\u id,presence:true
。它与其他验证不同(您可以设置一个不存在的id,它将是有效的,因为它存在,但它将是一个无效的位置),因此也保留
:location
验证。

验证关联和验证
\u id
列之间存在差异,但是大致的想法应该是同时验证
\u id
列和关联。

验证关联和验证
\u id
列之间的区别有很多不同之处,但是大致的想法应该是验证
\u id
列和关联。

您的
产品控制器是什么样子的?通常需要一个
if@product.save
块来捕获错误。然后可以更新视图。带有错误消息。是的,我正在@product.save中捕获任何错误,并可以在事后报告。我的问题主要是关于关联和在场验证器中的
thing
thing\u id
之间的区别。您的
ProductController
看起来像什么?通常需要一个
if@product.save
块来捕获错误。然后可以更新视图。带有错误消息。是的,我正在@product.save中捕获任何错误,并可以在事后报告。我的问题主要是关于关联和在场验证器中
thing
thing\u id
之间的区别。
<%= f.collection_select :location_id, @locations, :id, :name, include_blank: true %>