Reputation: 7874
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?
Upvotes: 6
Views: 3825
Reputation: 2293
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])
Upvotes: 16