Help with sorting results

Greetings,

I’m programming a section of my application that will store and list
stories. These stories should be sorted by three factors: genre,
order_by (such as time posted), and sort (ascending or descending). I
want to give my users the ability to easily sort through the list of
stories.

To achieve this, I’ve setup a named route:

map.sort_by ‘stories/sort_by/:genre/:order_by/:sort’, :controller =>
“stories”, :action => “index” (Both :order_by and :sort may be left
nil)

I’m stuck at the point of actually sorting and returning the results
(the controller logic). I’ve done some research, though am still quite
a newbie on rails. >< In your opinion, what would be the best way to
sort the stories based off of what is, and is not supplied to the
controller? For example, if only params(:genre) is supplied, I want
the list of stories to only display the specified genre. However, if
params(:order_by) is also supplied, the list would be of one genre and
listed, ASC or DESC by whatever :order_by is targeting.

Thanks in advance for you help!

~Dustin T.

nil)

I’m stuck at the point of actually sorting and returning the results
(the controller logic). I’ve done some research, though am still quite
a newbie on rails. >< In your opinion, what would be the best way to
sort the stories based off of what is, and is not supplied to the
controller? For example, if only params(:genre) is supplied, I want
the list of stories to only display the specified genre. However, if
params(:order_by) is also supplied, the list would be of one genre and
listed, ASC or DESC by whatever :order_by is targeting.

I’d do something like this:

if params[:genre]
conditions = [‘genre = ?’, params[:genre]
else
conditions = nil
end

params[:sort] = ‘asc’ unless [‘asc’, ‘desc’].include?
(params[:sort].downcase)

params[:order] = ‘title’ unless [‘title’, ‘created_at’,
‘some_field’].include?(params[:order_by].downcase)

Story.find(:all, :conditions => conditions, :order =>
“#{params[:order]} #{params[:sort]}”)

This way you check all the inputs and force them into something
reasonable if they aren’t what you want.

Thanks Philip!

That really helped. The application is running smoothly and everything
is working. :slight_smile:

~Dustin T.