Sorting an array of models

I have a model, listing, which belongs_to one or more categories. I need
the user to be able to search for categories by name (which I can do)
and have it return all the listings that belong to those categories.
This I can do.

However, what I need to do is take that list of listings and sort them
by one of their fields. This is a bit more complicated, without needing
to sort I could just do:

<% for category in @categories %>
<% for listing in category.listings %>
<%= DISPLAY CODE %>
<% end %>
<% end %>

But now I need to get an array of listings in my controller code, and
then sort that list. Is there an easy way to do that in Rails or do I
need to write my own sort code?

Thanks,

-Adam

On Apr 12, 2006, at 5:58 PM, Adam B. wrote:

Thanks,

-Adam


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


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

Look at Array#sort and Array#sort_by

-Ezra

Four ways to crack this nut.

  1. retrieve the data from the database in the order you want it. I
    think if you add an :order=>‘column’ to the belongs_to :category
    statement in your ‘listings.rb’ model file. This should default to this
    sort order

  2. use the association function: category.listings(:order=>‘name’)

  3. use a find statement: Listings.find_by_category(category,
    :order=>‘name’)

  4. get the collection from the association function, and sort those

sorted_array = category.listings.sort {|a,b| a.name <=> b.name}

For the most part, I prefer to let the database do the sorting for me.

On Thursday, April 13, 2006, at 2:58 AM, Adam B. wrote:

<% for listing in category.listings %>
-Adam


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


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

_Kevin

Thanks for the responses!

Four ways to crack this nut.

  1. retrieve the data from the database in the order you want it. I
    think if you add an :order=>‘column’ to the belongs_to :category
    statement in your ‘listings.rb’ model file. This should default to this
    sort order

This worked when I added the line to the line in categories.rb. I’m
guessing because it’s actually a habtm. :slight_smile:

  1. use the association function: category.listings(:order=>‘name’)

  2. use a find statement: Listings.find_by_category(category,
    :order=>‘name’)

  3. get the collection from the association function, and sort those

sorted_array = category.listings.sort {|a,b| a.name <=> b.name}

The problem with these is that I have to sort listings from
(potentially) a bunch of different categories.

For the most part, I prefer to let the database do the sorting for me.

_Kevin

Thanks again,

Adam