Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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!

like image 959
Vladimir Avatar asked Apr 17 '15 09:04

Vladimir


1 Answers

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"}, []))
like image 153
Wojtek Kruszewski Avatar answered Nov 09 '22 15:11

Wojtek Kruszewski