24

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

zzawaideh
  • 2,021
  • 1
  • 17
  • 25

3 Answers3

32

This was useful for me:

Model.where(...) | Model.where(...)
Corentin Geoffray
  • 705
  • 2
  • 7
  • 12
12

Use relation & relation:

Model.joins("join relationships ON user_id = followed_id").where("follower_id = {user.id}") & Model.where(:user_id => user.id)
fantactuka
  • 3,298
  • 19
  • 29
  • 6
    This forces ActiveRecord to put the results in an array eagerly. Can this be done with lazy loading? – zzawaideh Aug 29 '10 at 14:54
  • btw.. I did vote up your answer since it got me there part of the way. – zzawaideh Aug 30 '10 at 23:57
  • Shouldn't that be relation | relation? ActiveRecord::Relation quacks like an array and [1]&[2]==[] but [1]|[2]=[1,2]. – mtjhax Mar 28 '12 at 21:25
  • 10
    The `&` method on ActiveRecord::Relation is a alias for `merge`, and this alias has been removed as of Rails 3.0.9. It was removed for exactly the confusion that @MikeJohnson points out: it's not the appropriate operator. Use `relation.merge(other_relation)` instead. – Mitch Apr 11 '12 at 02:13
  • 10
    @zzawaideh just wondering if you have any idea how you solved this problem I am trying to retrieve two tables but need it as ActiveRecord::Relation not an array. any help would be much appreciated – Purple Hexagon Jun 28 '12 at 14:16
  • 3
    Wow, so "merge" puts them together with an AND. What would be the OR equivalent? – Arcolye Sep 13 '13 at 16:41
  • @Arcolye Did you ever figure out the OR equivalent to the relation.merge? – Neil Sep 11 '14 at 20:57
  • 1
    @Neil Watch this issue in the rails repo: https://github.com/rails/rails/pull/9052 – Arcolye Sep 12 '14 at 06:13
1

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