Forum: Ruby on Rails Sorting entries by clicking a table heading

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Df22d0adbdfb84c5a36c8b4388ee6b5e?d=identicon&s=25 Shane Riley (Guest)
on 2009-04-21 21:35
(Received via mailing list)
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.
5f94b9b346c2aa648a80bc259978e5bc?d=identicon&s=25 Colin Law (Guest)
on 2009-04-21 21:42
(Received via mailing list)
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 Riley <shanerileydotinfo@gmail.com>
Df22d0adbdfb84c5a36c8b4388ee6b5e?d=identicon&s=25 Shane Riley (Guest)
on 2009-04-21 21:44
(Received via mailing list)
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.
This topic is locked and can not be replied to.