Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two ActiveRecord Query results

Tags:

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

like image 608
zzawaideh Avatar asked Aug 29 '10 08:08

zzawaideh


People also ask

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is an ActiveRecord relation object?

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 does ActiveRecord base do?

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

What is ActiveRecord naming convention?

Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns. Foreign keys - These fields should be named following the pattern singularized_table_name_id (e.g., item_id , order_id ).


1 Answers

This was useful for me:

Model.where(...) | Model.where(...) 
like image 104
Corentin Geoffray Avatar answered Oct 13 '22 09:10

Corentin Geoffray