Rails Nested Eager Loading?

时间:2015-06-25 18:44:15

标签: ruby-on-rails dry eager-loading

Lets say we have a nested set up where class Foo belongs_to :object has_many :bar end class Bar belongs_to :foo has_one :abc end class Abc belongs_to :bar end And I want to eager load abc from foo. What would be the best way to do this? Currently this doesn't seem to work: object.foos(include: {bar: :abc}) My goal is to avoid making code like this: object.foos.any? do |f| f.bar.abc.method_1 && f.bar.abc.method_2 && f.bar.abc.method_3 end And move to more dry code like: object.foos(rails_magic).any? do |x| x.method_1 && x.method_2 && x.method_3 end

1 个答案:

答案 0 :(得分:0)

因为你不能在除了类之外的任何东西上进行嵌套的eager加载,所以重新排列你的查询是有意义的:

Foo.includes(:object, :bar => :abc).where('object_id = ?', object.id).references(:object).each do |f|
...
end

该查询正在急切加载Object,并通过自己与ABC的关联加载Bar