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!
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"}, []))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With