【发布时间】:2018-12-03 19:53:23
【问题描述】:
我是 Rails 新手,我不确定如何设置组合框,以便在浏览器中将其显示为“必需”。我有一个Product 和一个Location,并且产品中应该需要位置:
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 人都知道的东西。
【问题讨论】:
-
您的
ProductController是什么样的?通常你需要一个if @product.save块来捕获错误。然后您可以更新视图。带有错误消息。 -
是的,我在@product.save 中发现了任何错误,并且可以在事后报告它们。我的问题主要是关于
thing和thing_id在关联和存在验证器中的区别。