Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two ActiveRecord arrays and order by created_at

books = Book.find(:all)
articles = Articles.find(:all)

By reading from http://guides.rubyonrails.org/layouts_and_rendering.html I knew that I could do something like:

<%= render :partial => [customer1, employee1, customer2, employee2] %>

and it would use _customer and _employee partials as appropriate.

So I want to do something like that:

materials = books + articles
materials.sort_by_created_at

and in the view:

<%= render :partial => materials %>

How to do the merging and sorting of two ActiveRecord arrays???Thanks for help!

like image 391
PeterWong Avatar asked Aug 29 '10 05:08

PeterWong


2 Answers

You're very close. Concatenating the arrays is done with the plus sign:

materials = books + articles

Sorting the combined array can be done by calling the sort_by method (mixed in from Enumerable) and passing in the attribute prefixed with &:

materials.sort_by(&:created_at)

This won't be good performance-wise for large result sets. You might consider deriving the Book and Article models from a parent class (like Material) if they are similar, using STI (Single Table Inheritance) to store them in the same table, and using find with an order clause, so the database can do the sorting for you.

like image 93
zetetic Avatar answered Oct 25 '22 12:10

zetetic


You can also use Array#concat to merge two arrays.

like image 6
ryancheung Avatar answered Oct 25 '22 13:10

ryancheung