Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord: find_by_sql and includes

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?

like image 458
Tsuneo Yoshioka Avatar asked Nov 19 '14 05:11

Tsuneo Yoshioka


1 Answers

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])
like image 157
gmcnaughton Avatar answered Oct 05 '22 02:10

gmcnaughton