The SitePoint Forums have moved.

You can now find them here.
This forum is now closed to new posts, but you can browse existing content.
You can find out more information about the move and how to open a new account (if necessary) here.
If you get stuck you can get support by emailing forums@sitepoint.com

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Sorty_by in nested tables

I need to do an : order => on an attribute in a double nested table, but I can't get it to work.

class CabinetNominee
belongs_to :cabinet_pick
end

class CabinetPick
belongs_to :cabinet_position
end

class CabinetNominee
end

In my views, I can loop through
@cabinet_nominee.each do |c|
c.cabinet_pick.cabinet_position.name
end

just fine. But, in my controller, I need to order my @cabinet_nominee collection by
cabinet_pick.cabinet_position.name DESC, and I can't figure out how. I have used :through and :join and .sort_by and on and on. Any one have any ideas?

If all you were doing was picking out the names and then ordering them, you could do this:

Code:

names = @cabinet_nominees.collect{|c| c.cabinet_pick.cabinet_position.name}
for name in names.sort
#output name
end

But I expect you want more information than just the names. The best answer depends on what information you want to retrieve. I expect, as you are collecting information from three tables, the best solution would be to use a custom SQL call. If you try joining three or more table together using standard ActiveRecord calls things really start to grind. It's usually much faster to gather all the data in a single SQL call.

Can you post your table fields and what information you want to display? It should then be possible to suggest a single SQL call that will gather all the information you want.

Thanks for the reply. The majority of what I need to display comes from :cabinet_nominee table. I only need to display the attributes full_name from :cabinet_pick and name from :cabinet_position. Again, all of this works fine in the view. I would just like to order my @cabinet_nominee by cabinet_position.name.

However, it may be quite slow if it makes a SQL call to look up each cabinet_pick and then each cabinet_position. You may need to look at the :through options in the find call used to generate @cabinet_nominee is performance if an issue.