How to set preload scope for Rails Associations::Preloader?

风格不统一 提交于 2019-12-01 02:11:21

问题


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.

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

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!


回答1:


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.

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"}, []))


来源:https://stackoverflow.com/questions/29695265/how-to-set-preload-scope-for-rails-associationspreloader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!