如何防止使用named_scope创建n + 1个查询

时间:2015-09-18 14:53:35

标签: sql ruby-on-rails activerecord rails-activerecord arel

在引用已加载的模型列表时,阻止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

使用named_scope时阻止此额外查询的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

只要您使用where,就会触发另一个查询。如果您认为内存中包含所有记录,请将生成的活动记录关系视为数组,而不是SQL。使用select等数组方法代替where。也许:

@checklists[0].checklist_items.select {|ci| ci.active == true}