I have a few massive SQL request involving join across various models in my rails application. A single request can involve 6 to 10 tables.
To run the request faster I w
Was looking for this, and was helped by the other answers, but there are some error in both, e.g. A.join(...
should be a.join(...
.
And I also missed how to build an ActiveRecord::Relation
.
Here is how to build an ActiveRecord::Relation
, in Rails 4
a = A.arel_table
b = B.arel_table
subsel = B.select(b[:a_id]).where(b[:c].gt('4')).as('sub_select')
joins = a.join(subsel).on(subsel[:a_id].eq(a[:id])).join_sources
rel = A.joins(joins)
rel.to_sql
#=> "SELECT `a`.* FROM `a` INNER JOIN (SELECT `b`.`a_id` FROM `b` WHERE (`b`.`c` > 4)) sub_select ON sub_select.`a_id` = `a`.`id`"