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?
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).
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.
@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
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