Activerecord 预加载已加载关系的关联
我想为已经加载的关系预加载关联,这样可以避免N+1问题。问题是我无法重写原始查询,因为我只想在某些情况下预加载关联,如下所示:Activerecord 预加载已加载关系的关联,activerecord,ruby-on-rails-5,Activerecord,Ruby On Rails 5,我想为已经加载的关系预加载关联,这样可以避免N+1问题。问题是我无法重写原始查询,因为我只想在某些情况下预加载关联,如下所示: results = SomeModel.where(some_condition).load # do some stuff with the results if some_condition preload_associations(results, [:some_association, :another_association]) # do some s
results = SomeModel.where(some_condition).load
# do some stuff with the results
if some_condition
preload_associations(results, [:some_association, :another_association])
# do some stuff with the results and preloaded associations
end
我发现这只适用于rails的早期版本,使用这种方法。我知道该方法仅用于内部使用,但我想知道是否有一种方法可以实现rails 5+的相同功能?现代rails使用助手类来处理: 在你的例子中,我相信你会这样做:
results = SomeModel.where(some_condition).load
# do some stuff with the results
if some_condition
ActiveRecord::Associations::Preloader.new.preload(results, [:some_association, :another_association])
# do some stuff with the results and preloaded associations
end
现代rails使用助手类来处理: 在你的例子中,我相信你会这样做:
results = SomeModel.where(some_condition).load
# do some stuff with the results
if some_condition
ActiveRecord::Associations::Preloader.new.preload(results, [:some_association, :another_association])
# do some stuff with the results and preloaded associations
end
那么
results=SomeModel.where(some_条件)呢;结果.包括(:某些关联,:另一个关联)如果某个条件
?我在生成条件之前对关联做了一些处理,因此该点已加载。如果在该点包含关联,结果将再次加载。那么results=SomeModel.where(some_条件)呢;结果.包括(:某些关联,:另一个关联)如果某个条件
?我在生成条件之前对关联做了一些处理,因此该点已加载。如果在该点包含关联,结果将再次加载。