Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine ActiveRecord objects?

I'm wondering if there's an efficient way to combine the results of multiple ActiveRecord objects in Rails. For example, I might make three individual calls to three individual tables, and I want the results combined, and sorted by a common column.

Here's a super basic code example that will hopefully make my question easier to understand:

@results1 = Table1.find(:all)  
@results2 = Table2.find(:all)  
@results3 = Table3.find(:all)  

@combined_results_sorted_by_date_column = (how?)

As suggested by others, here's one solution to the problem.

@combined_results = @result1 + @result2 + @result3
@combined_results.sort! {|x,y| x.date <=> y.date}

What if I want to sort by date, but Table3 refers to the "created_on" column as date?

like image 795
Jess Avatar asked Jul 02 '09 17:07

Jess


People also ask

What is an ActiveRecord relation?

An instance of ActiveRecord::Base is an object that represents a specific row of your database (or might be saved into the database). Whereas an instance of ActiveRecord::Relation is a representation of a query that can be run against your database (but wasn't run yet).

What is Active Record in Ruby?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

@results1 = Table1.find(:all)
@results2 = Table2.find(:all)
@results3 = Table3.find(:all)

@combined_results_sorted_by_date_column =
   (@results1 + @results2 + @results3).sort_by(&:date)

What if I want to sort by date, but Table3 refers to the "created_on" column as date?

class Table3
  alias_method :date, :created_on
end

or simply

class Table3
  alias date created_on
end
like image 190
Lars Haugseth Avatar answered Sep 25 '22 12:09

Lars Haugseth