Sorted Homepage With Ruby on Rails
Ruby on Rails Homepage Sorting
I have a magazine site with a typical homepage that features the latest items in each category. Something that has been subtly gnawing at my sanity for a long time is that items were showing up in the order I placed them in my view, not based on creation date. So if there were a whole bunch of news songs, for example, you’d never know it because they were always at the bottom of the page, and if the films hadn’t been updated in a dogs age - they still showed up at the very top of the page… It was causing the site to suffer by never looking as current as it could. I knew this could be changed but I kept forgetting to look into it. Tonight I did.
The first thing that occurred to me was to create an array of hashes - each hash would contain a date, and a partial:
items = Array.new
items << { :date => @albums.created_at, :partial => 'albums' }
items << { :date => @songs.created_at, :partial => 'songs' }
Now I just needed to figure out how to sort the array. It turned out to be very easy:
items.sort { |a,b| b[:date] <=> a[:date] }
So what I ended up doing to get all of this ugliness out of my controller was this: I created a new Home.rb model without ActiveRecord with a def self.right_column method that takes the instance variables as arguments and returns a sorted array of partials to display.
class Home
def self.right_column(@albums,@songs)
items = Array.new
items << { :date => @albums.created_at, :partial => 'albums' }
items << { :date => @songs.created_at, :partial => 'songs' }
items.sort { |a,b| b[:date] <=> a[:date] }
end
end
So my controller looks like this:
def index
@album = Album.recent
@songs. Song.recent
@right_column = Home.right_column(@albums,@songs)
end
In my view I just iterate through the array, printing out the partials in the order sorted by most recent:
<% @right_column.each do |item| %>
<%= render :partial => item[:partial] %>
<% end %>
It works like a charm and I think it will help keep the site looking current!
I am available for Ruby on Rails consulting work – get in touch to learn more.