【问题标题】:has_many with unsaved default in collectionhas_many 集合中未保存的默认值
【发布时间】:2021-07-16 20:12:11
【问题描述】:

我认为这将是一件简单的事情,但不幸的是我找不到使用默认条目创建集合的方法。

有模型Entry可以被一个或多个filter_entries过滤。 当没有关联时,应该有一个后备。因为我不想在数据库中为 100000 个条目创建默认关联。

目前我做了一个数组,它返回一个默认条目。

class Entry
  belongs_to :object
  has_many :entry_filters, dependent: :destroy

  def entry_filters
    super.presence || [EntryFilter.new(filter: default_filter)]
  end
  
  private

  def default_entry
    object.filters.find_by(default: true)
  end
end

具有关联的条目

Entry.first.entry_filters
=> [#<EntryFilter:0x00007f4b39cb16d8
  id: 1,
  entry_type: "Entry",
  entry_id: 1,
  filter_id: 1>]
Entry.first.entry_filters.class
=> EntrySegment::ActiveRecord_Associations_CollectionProxy

没有关联的条目

Entry.second.entry_filters
=> [#<EntryFilter:0x000055e9060ac608
  id: nil,
  entry_type: nil,
  entry_id: nil,
  filter_id: 1>]
Entry.second.entry_filters.class
=> Array

它有效,但我想使用一个集合,比如当有一个真正的关联链接到条目时。

有没有办法使用ActiveRecord::Associations::HasManyAssociation 来伪造该集合? 我尝试了几种方法,但每种方法都会创建关联而不是构建关联。

Entry.second.association(:entry_filters).writer([EntryFilter.new(filter: Filter.first)])
=> [#<EntryFilter:0x00007f90d0b38d88 id: 2, entry_type: "Entry", entry_id: 2, filter_id: 1>]
Entry.second.association(:entry_filters).replace([EntryFilter.new(filter: Filter.first)])
=> [#<EntryFilter:0x00007f90d0a457c8 id: 3, entry_type: "Entry", entry_id: 2, filter_id: 1>]
Entry.second.association(:entry_filters).concat([EntryFilter.new(filter: Filter.first)])
=> [#<EntryFilter:0x00007f90d0a637a5 id: 4, entry_type: "Entry", entry_id: 2, filter_id: 1>]

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    你可以使用.build收集方法做你想做的事:

    def entry_filters
      filters = super
      filters.build(filter: default_filter) if filters.blank?
      filters
    end
    

    .build 方法实例化一个新的关联对象(不保存),设置外键,并将其添加到内存中对象的集合中。在普通用法中,您可以将其称为&lt;entry_obj&gt;.entry_filters.build(filter: ...)。但是,您不能在 .entry_filters 本身内部执行此操作,否则最终会出现无限递归。因此,我们首先调用super 来获取集合,然后如果集合当前为空,则调用.build。

    > Entry.new.entry_filters
    => #<ActiveRecord::Associations::CollectionProxy [#<EntryFilter id: nil, 
    filter_id: ... ]
    

    当您在父条目上调用.save 时,它也会在此时保存新的条目过滤器。

    【讨论】:

    • 我忘记在我的示例代码中添加.presence。所以空白集合返回 nil 并且数组将被返回。 .build 返回与 .new 相同的结果。在您的代码中,一个已初始化的对象。但我想要的是一个具有该初始化对象的集合。
    • 抱歉,我脑筋急转弯,在将代码放入答案后对其进行了调整。调用 .build 会返回新对象,但也会将它返回到集合中,因此您只需返回 filters 任何一种方式,它都会执行您想要的操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    相关资源
    最近更新 更多