【问题标题】:Rails 5 optional has_many associationsRails 5 可选的 has_many 关联
【发布时间】:2018-11-14 13:50:43
【问题描述】:

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 不是必须的。我面临的问题是,如果我不添加任何捐助者关系,则使用捐助者 ID 创建 donor_relationship 的空记录。在 Rails 4 中不会发生这种情况。

我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5 has-many


    【解决方案1】:

    accepts_nested_attributes_for ignore blank values

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

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

    【讨论】:

      【解决方案2】:

      您可以使用reject_if 选项:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多