I would like to use find_by_sql and includes at the same time.
I use find_by_sql because I write select inside from to utilize index. Somehow, index is ignored if I use left join.
But, find_by_sql does not return ActiveRecord_Relation but returns Array objects, so I cannot write
like Model.find_by_sql("select * from (select * from table limit 10)table left join rel_table on ...").includes(:rel_table,...) .
I can run two queries and hand-includes after that. Is there any way to solve it as one SQL?
You can't call includes
on the resulting array, but you can call the Rails preloader manually to do the same thing.
See ARel mimic includes with find_by_sql.
array = Model.find_by_sql("select * from ...")
# Rails 3 and 4.0.x
ActiveRecord::Associations::Preloader.new(array, [:rel_table]).run
# Rails 4.1+
ActiveRecord::Associations::Preloader.new.preload(array, [:rel_table])
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