8

I need get union of two ActiveRecord::Relation objects in such a way that the resultant should be another active record relation. How can I accomplish this?

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
MayankS
  • 446
  • 1
  • 3
  • 17
  • ' union of two active records ' mean? – Nithin Apr 23 '14 at 12:57
  • I have two active records for same model but with different records. I want to combine both of those active records and the result should be another active record. Does that answer your question? – MayankS Apr 23 '14 at 13:06
  • You've got to give some code to go off of, otherwise people have no idea how to help. – kddeisz Apr 23 '14 at 13:18
  • possible duplicate of [Combine two ActiveRecord::Relation objects](http://stackoverflow.com/questions/9540801/combine-two-activerecordrelation-objects) – Claudio Floreani Sep 24 '15 at 20:19

1 Answers1

11

Update for Rails 5

ActiveRecord now brings built-in support for UNION/OR queries! Now you can (the following examples are taken, as-is, from this nice post. Make sure you read the full post for more tricks and limitations):

Post.where(id: 1).or(Post.where(title: 'Learn Rails'))

or combine with having:

posts.having('id > 3').or(posts.having('title like "Hi%"'))

or even mix with scopes:

Post.contains_blog_keyword.or(Post.where('id > 3'))

Original answer follows

I do not think that AR provides a union method. You can either execute raw SQL and use SQL's UNION or perform the 2 different queries and union the results in Rails.

Alternatively you could take a look in these custom "hacks": ActiveRecord Query Union or https://coderwall.com/p/9hohaa

Community
  • 1
  • 1
Kostas Rousis
  • 5,918
  • 1
  • 33
  • 38