Rails 5 个可选 has_many 关联

Rails 5 optional has_many associations

app/models/donor.rb

has_many :donor_relationships
accepts_nested_attributes_for :donor_relationships, :allow_destroy => true

app/models/donor_relationship.rb

belongs_to :donor, optional: true

我正在使用捐赠者形式的 f.fields_for 并同时创建 donordonor_relationships

donor_relationships不是必须的。我面临的问题是,如果我不添加任何 donor_relationships,则会使用捐赠者 ID 创建 donor_relationship 的空记录。在rails 4 不会发生这种情况。

我该如何解决这个问题?

您可以使用 reject_if 选项:

accepts_nested_attributes_for :donor_relationships, 
  allow_destroy: true,
  reject_if: proc { |attributes| attributes['important_field'].blank? }

accepts_nested_attributes_for ignore blank values

您可以向 accepts_nested_attributes 方法添加 reject_if 条件。假设您的 donor_relationship 具有名称属性(您可以使用 relationship_id 或任何有意义的属性):

accepts_nested_attributes_for :donor_relationships,
                              :allow_destroy => true,
                              :reject_if => lambda { |c| c[:name].blank? }`