Sorting entries by clicking a table heading


#1

Hey, everybody. I’ve just started learning Rails this week, and am
trying to reinforce what I’ve learned so far by writing a simple
listing site. I’ve got all of the basics working, but thought it would
be nice to add sorting functionality when a user clicks on a column
heading. I thought I had it all sorted out, but it seems that nothing
happens when you click the links. Here’s what I’ve got written to make
it work (note: I’m using Rails 2.2.2 for this example, since the
PragProg Rails book uses that version).

First, in the view I’ve got the heading links being generated like
this:
<%= link_to “Address”, {:action => “index”, :order_by => “:address1” }
%>
Then in the controller, I’ve got this listing for my index (the logic
could be shortened up a bit, I know. Just trying to make it clear for
me)
def index
if params[:order_by]
@properties = Property.find(:all, :order => params[:order_by])
else
@properties = Property.find(:all)
end

Everything still works after this addition, and clicking on a heading
link sends me to the index listing, but the order does not change. In
Terminal, I see this for my DB query:
Parameters: {“order_by”=>":address1"}
Property Load (1.0ms) SELECT * FROM “properties” ORDER BY :address1

Should I be doing this some other way? Trying to search for a solution
through Google takes me to a bunch of old posts about checking out
this Wiki article (http://wiki.rubyonrails.org/rails/pages/SortHelper)
but there’s nothing there.


#2

If you look carefully at the SQL you will see that you are ordering by
:address1. I am guessing that :address1 is not the column name.

2009/4/21 Shane R. removed_email_address@domain.invalid


#3

Actually, before this post appeared I figured it out. I do have a
column named address1 (the same link structure failed to work for all
columns), but I needed to pass the column name as-is instead of as a
parameter (ie: remove the :). Thanks for the response, though.