Yeah, that's a problem I haven't actually tackled myself yet. :P  If you 
notice, I did this:

  <th><%= sort_link('Status', 'status_id') %></th>

Which does the sort by the numeric value of the id for the status, rather than 
the text the user sees.  Very bush-league.

So I fixed it just now ;-) like so:

  - Add an :include clause in the .find call to bring the fields from the child 
table into the SQL generated by AR.
  - Changed my field references to include the table names, for any fields 
whose names are in both tables.

# controller
  def index
    order_by = params[:order_by] || 'projects.name' #<-- added the table 
prefix, since both Projects and Statuses have name fields.
    @projects = Project.find(:all, :order => order_by, :include => 'status') 
#<-- The :include causes rails to join both tables in the resulting query.

Then the view becomes:

# view
  <th><%= sort_link('Name', 'projects.name') %></th>
  <th><%= sort_link('Grant number', 'grant_number') %></th>
  <th><%= sort_link('Status', 'statuses.name') %></th>

This seems to work pretty well.  I'm not sure how well it would scale if you've 
got e.g., fifteen different child objects you need to bring in.

The {:title => } stuff causes the <a> tags to have a title attribute, which 
gets shown in a tooltip when the user hovers over the link.  (link_to takes an 
optional hash of tag attributes.)

HTH,

-Roy

-----Original Message-----
From: [email protected] [mailto:[EMAIL PROTECTED] On Behalf Of 
bingo bob
Sent: Wednesday, October 22, 2008 2:39 AM
To: [email protected]
Subject: [Rails] Re: sorting in different ways (with the same index action)



Thanks, this is great. It works and I can see the value of the helper!
Makes the controller code so much easier. Seem "right".

I could do with a bit more help though.

1) Out of interest - how do you use the [:title => "Sort by #{show_text}"] bit?

2) Most importantly, I got this working when I sort by columns in my news_items 
table, e.g. news_item.date BUT I can't get it to work for me as I ahve 
relationships built up such that I have, news_item.stock and a stock has a 
name. How would I use this to sort my news_items by the names of fields of 
items with them, e.g. a news_item stock name, or a news_item news_type name.

thought i could do something like ...

    <th><%= sort_link('Sector', 'news_item.sector.name') %></th>

But I can't, the SQL select generated blows up.

I might have set my relationships up wrong, but I don't think so.

BB
--
Posted via http://www.ruby-forum.com/.



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to