| 1. | Herb - 05 28, 2007 @ 01:22PM |
Seeing as its the first google hit and no one has posted a comment... thanks works great for me!
Of all the things I hate doing, column sorting has to be top on my list. It always seems to be more difficult than it should be. Here's my take on a really simple way to implement column sorting for your Rails application. I call it Super Cool Simple Column Sorting, or SCSCS. That's pronounced 'ssssssss'.
The first part is the HTML helper.
def sort_link(title, column, options = {})
condition = options[:unless] if options.has_key?(:unless)
sort_dir = params[:d] == 'up' ? 'down' : 'up'
link_to_unless condition, title, request.parameters.merge( {:c => column, :d => sort_dir} )
end
It takes the title you wish to display, the name of the column you wish to sort, and any extra options you wish to add to the link. You can also pass an :unless flag to turn the link on or off. Put this in a helper somewhere, maybe application_helper.rb.
To use it...
<%= sort_link 'Company', :company_name %>
This will default to sorting up, or ASC, and will toggle up or down automatically.
Now you just need the SQL helper.
def sort_order(default)
"#{(params[:c] || default.to_s).gsub(/[\s;'\"]/,'')} #{params[:d] == 'down' ? 'DESC' : 'ASC'}"
end
Put this somewhere the controller can see it, maybe application.rb. Then just call it in the query in your controller.
def list
@applications = Application.find(:all, :order => sort_order('created_at'))
end
The sort_order method takes the default column you wish to sort on.
I really like this simple helper based approach. It's not quite as slick as making a plugin, but it's easier to tweak it for different cases, and less than 10 lines.
| 1. | Herb - 05 28, 2007 @ 01:22PM |
Seeing as its the first google hit and no one has posted a comment... thanks works great for me!
| 7. | Rich Allen - 12 16, 2007 @ 05:59AM |
Exactly what I have been looking for, thanks!
Post a Comment