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?
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.
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.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With