How to set preload area for Rails associations :: Preloader?

I need to pre-establish model associations with complex conditions. NO, includes does not work for me. It generates the wrong SQL for my task.

I look at ActiveRecord::Associations::Preloader and find that it takes the 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 not find any example of its use. What is preload_scope in this case? And how can I use it to filter associations? Thanks!

+6
source share
1 answer

ActiveRecord does not disclose this through #preloads with respect to: https://github.com/rails/rails/blob/0aefa97689d001ca9a98db76bbad1bbbb0e51c9c/activerecord/lib/active_record/relation.rb#L663 - as you can see, only parameters are passed in associations.

You can contact the internal components of ActiveRecord and directly call Preloader:

 rows = Projects.all.to_a ActiveRecord::Associations::Preloader.new.preload(rows, :current_task, Struct.new(:values, :bind_values).new({where: "active"}, [])) 
+2
source

Source: https://habr.com/ru/post/985334/


All Articles