如何设置Rails Associations :: Preloader的预加载范围? [英] How to set preload scope for Rails Associations::Preloader?
问题描述
我需要预加载具有复杂条件的模型关联。不,包含
对我不起作用。
I need to preload associations of the model with complex conditions. NO, includes
doesn't work for me. It generate wrong SQL for my task.
我看看 ActiveRecord :: Associations :: Preloader
和发现他接受了 preload_scope
参数:
I take a look to the ActiveRecord::Associations::Preloader
and find that he take an preload_scope
argument:
http://apidock.com/rails/v4.2.1/ActiveRecord/Associations/Preloader/preload
def preload(records, associations, preload_scope = nil)
# ...
end
但是我找不到使用它的任何示例。在这种情况下, preload_scope
是什么?以及如何使用它来过滤关联?
谢谢!
But I can't find any example using it. What is preload_scope
in this case? And how I can use it for filtering associations?
Thanks!
推荐答案
ActiveRecord不会通过 #preloads $ c公开此内容关系上的$ c>:
https ://github.com/rails/rails/blob/0aefa97689d001ca9a98db76bbad1bbbb0e51c9c/activerecord/lib/active_record/relation.rb#L663 –您只能看到传递了记录和关联参数。
ActiveRecord doesn't expose this through #preloads
on relation:
https://github.com/rails/rails/blob/0aefa97689d001ca9a98db76bbad1bbbb0e51c9c/activerecord/lib/active_record/relation.rb#L663 – as you can see only records and associations parameters are passed.
您可以进入ActiveRecord内部并直接调用Preloader:
You can reach into ActiveRecord internals and call Preloader directly:
rows = Projects.all.to_a
ActiveRecord::Associations::Preloader.new.preload(rows, :current_task, Struct.new(:values, :bind_values).new({where: "active"}, []))
这篇关于如何设置Rails Associations :: Preloader的预加载范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!