【问题标题】:How to show required form field for association in rails?如何在rails中显示关联所需的表单字段?
【发布时间】: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 中发现了任何错误,并且可以在事后报告它们。我的问题主要是关于 thingthing_id 在关联和存在验证器中的区别。

标签: ruby-on-rails validation


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    有一个bunchofposts关于验证关联和验证_id列之间的差异,但粗略的想法应该是验证_id和 em> 协会。

    【讨论】:

      猜你喜欢
      • 2015-06-09
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 2016-10-26
      • 2011-05-25
      相关资源
      最近更新 更多