我有一个Profile
模型,我正在尝试查看该个人资料是否在过去使用过任何其他名称。我想出了添加AdditionalName
模型的方法,其关联为Profile has_many AdditionalName
。在表格中,我希望他们填写最多5个其他名称。我从this question看到可以建立x.times
,并使用f.fields_for :additional_names
显示5个其他名称。问题是,即使我没有填写任何内容,也将在我提交表单时保存全部5个信息。 AdditionalName
记录是否只有在输入字段中填写内容时才保存?
additional_name.rb
class AdditionalName < ApplicationRecord
belongs_to :profile
end
profile.rb
class Profile < ApplicationRecord
has_many :additional_names
accepts_nested_attributes_for :additional_names
end
控制器:
def new
existing_additional_names = @profile.additional_names.count
(5 - existing_additional_names).times do
@current_object.additional_names.build
end
表格:
<%= form_with model: @profile, url: wizard_path, method: :patch, local: true do |f| %>
<div class="form-row">
<%= f.fields_for :additional_names do |additional_names_form| %>
<%= additional_names_form.hidden_field :id %>
<div class="form-group col-md-6">
<div class="mx-auto">
<%= additional_names_form.label :name, "Full name" %>
<%= additional_names_form.text_field :name, class: "form-control", id: "ignore-button-disable" %>
</div>
</div>
<% end %>
</div>
<div class="row">
<div class="col-md-6 my-2">
<%= f.submit 'Continue', class: 'btn btn-primary w-100' %>
</div>
</div>
<% end %>
答案 0 :(得分:1)
如果只希望在设置了特定属性的情况下才创建嵌套记录,则不需要自定义逻辑。您可以在模型中通过lambda调用选项:reject_if到accepts_nested_attributes_for
进行调用。
根据定义:
允许您指定Proc或Symbol指向一种方法,该方法检查是否应为特定属性哈希构建记录。
accepts_nested_attributes_for :additional_names,
reject_if: -> { |attributes| attributes['name'].blank? }
答案 1 :(得分:0)
我只需要覆盖模型中的additional_names_attributes=
:
def additional_names_attributes=(additional_name_attributes)
additional_name_attributes.values.each do |additional_name_attribute|
unless additional_name_attribute[:name].empty?
additional_name = AdditionalName.find_or_create_by(additional_name_attribute)
self.additional_names << additional_name
end
end
end