Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 892
MayankS Avatar asked Apr 23 '14 12:04

MayankS


People also ask

What is ActiveRecord relation in rails?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.

What is active record pattern in rails?

The active record pattern is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database.

What is ActiveRecord :: Base in Rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.


1 Answers

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

like image 59
Kostas Rousis Avatar answered Sep 17 '22 18:09

Kostas Rousis