在引用已加载的模型列表时,阻止ActiveRecord进行不必要查询的最佳方法是什么?
class Checklist
has_many :checklist_items
scope :active, where(active: true)
end
class ChecklistItem
belongs_to :checklist
scope :active, where(active: true)
end
@checklists = Checklist.active.includes(:checklist_items).where(checklist_items: {active: true})
# Works fine, does NOT make extra SQL query
@checklists[0].checklist_items
# Makes extra query. How do I prevent this?
@checklists[0].checklist_items.active
答案 0 :(得分:0)
只要您使用where
,就会触发另一个查询。如果您认为内存中包含所有记录,请将生成的活动记录关系视为数组,而不是SQL。使用select
等数组方法代替where
。也许:
@checklists[0].checklist_items.select {|ci| ci.active == true}