【发布时间】: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