ruby-on-rails - 如何在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 人都知道的东西。
解决方案
尝试使用validates :location_id, presence: true
. 它与其他验证不同(您可以设置一个不存在的 id,它将有效,因为它存在但它将是一个无效的位置),所以:location
也离开验证。
推荐阅读
- javascript - html中如何使用ajax进行php后台提交
- flutter - 颤动中从孩子到父母的回调
- azure - Windows 服务的 Azure 构建任务:- $(build.artifactstagingdirectory) 下没有 zip
- php - 将 scssphp 与 cakephp 一起使用
- javascript - Slick Carousel 在移动设备上显示垂直而不是水平
- python - 如何按天下载电子邮件附件?
- vim - 在 gVim 中插入特定字符串而不是制表符或空格
- php - 对子数组进行排序,以便每个子数组中的对应值按数字顺序排列?
- java - 如何使用单独的 Mysql 表使用 JPA 实现枚举
- python - 训练多标签分类模型时内存不足