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



我是rails的新手,不知道如何设置组合框,以便在浏览器中显示为"必需"。我有ProductLocation,产品中应该需要位置:

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

在我的新产品表单中,我有一个助手,它显示该字段是必需的,但我不确定如何最好地使用这个关联的位置。当我尝试将其映射到:location属性时,如下所示:

<%= form_for @product do |f| %>
<%= show_label f, :location %>
<%= f.collection_select :location, @locations, :id, :name, include_blank: true %>
<%= f.submit %>
<% end %>
# helper
def show_label(f, attr)
required = f.object.class.validators_on(attr)
.any? { |v| v.kind_of?(ActiveModel::Validations::PresenceValidator) }
label = attr.to_s + required ? '*' : ''
label
end 

show_label助手正确地看到:location是必需的,但模型本身在表单发布后无法验证,因为这里的位置是一个字符串(位置的:id(,而不是实际的Location

当我使用:location_id:时

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

那么show_label没有看到:location_id是必需的属性,所以我没有得到必需的字段注释,在保存模型时,位置得到了正确的保存。

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

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

关于验证关联和验证_id列之间的区别,有很多文章,但大致的想法应该是验证_id关联。

最新更新