首页 > 解决方案 > 如何在rails中显示关联所需的表单字段?

问题描述

我是 Rails 新手,我不确定如何设置组合框,以便它可以在浏览器中显示为“必需”。我有 aProduct和 a 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 人都知道的东西。

标签: ruby-on-railsvalidation

解决方案


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


推荐阅读