Union of two active record relations should be another active record in ruby on rails

activerecord, ruby-on-rails

Solution

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

Problem

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?

Original source

Related problems