Rails combines two ActiveRecord :: Relation

I have a "Profile" model and two ActiveRecord :: Relations for this model. The SQL query for the first relation is very large. Second -

Profile.where(:id => 1)

      

I want to add a second relation to the first. So, as a result, the second relation will contain the first prrofile.

I tried

first.merge(second)

      

but returns an empty relation. Rails version is 3.2.2 Of course, the result must also be a relation. I need to add .limit () and .paginate () to this relation.

+3


source to share


2 answers


You can use additional ones. where clauses for an existing relationship, thus:

relation = Thing.joins(:associated_things => [:users, :still_more_things]).where(:condition => true)
new_relation = relation.where(:id => 1)

      



This will combine the new "where" with any existing one using AND. ActiveRecord :: Relation does not support attaching "wheres" to ORs, if you need to, check Squeel (https://github.com/ernie/squeel) if you are using Rails 3.1+ or meta_where (https: // github. com / ernie / meta_where) for 3.0.

+2


source


The merge overwrites the values ​​for the same keys in the first relation with the values ​​from the merged relation.



0


source







All Articles