zzawaideh
zzawaideh

Reputation: 2011

Combine two ActiveRecord Query results

I currently have two active record queries that I would like to combine together

joins("join relationships ON user_id = followed_id").
              where("follower_id = #{user.id}")

and

where(:user_id => user.id)

Basically I want the results of the second one to appear with the first similar to a UNION statement in SQL. Can it be done in ActiveRecord in this way?

I would prefer to use a union rather that have to join all the followed_ids in a string and use the IN clause in sql.

Any ideas?

-----Edit------ I am looking for a way to get this to work with lazy loading

Upvotes: 24

Views: 30536

Answers (3)

This was useful for me:

An updated version of Rails/ActiveRecord may support this syntax natively. It would look similar to:

Model.where(foo: 'bar').or.where(bar: 'bar')

Or you can, simply sticking with the following works great:

Model.where('foo= ? OR bar= ?', 'bar', 'bar')

referred to this link

Upvotes: 1

Corentin Geoffray
Corentin Geoffray

Reputation: 695

This was useful for me:

Model.where(...) | Model.where(...)

Upvotes: 31

fantactuka
fantactuka

Reputation: 3334

Use relation & relation:

Model.joins("join relationships ON user_id = followed_id").where("follower_id = {user.id}") & Model.where(:user_id => user.id)

Upvotes: 12

Related Questions