Forum: Ruby on Rails resorting a dataset

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.
Steve O. (Guest)
on 2005-12-26 21:29
(Received via mailing list)
Quick question to see how I might re-sort an Activerecord data set.
Let's
say I have this table:

tablename: testscores
| id | student | score | avg_for_year
1, steve, 85, 82
2, tom, 84, 92,
3, jim, 92, 95

In my controller, I have something like:
t= Testscores.find(:all, :order => "score DESC", :limit => 2)

...where it would return the records for Jim and Steve....

My question is:
Is it possible to sort the resulting array "t" by name?

Where if I want to render this collection in a view, I could render it
sorted by the students name, rather than their test score.

The key point is that I am taking only 2 of the 3 records based on their
test score and then sorting the returned students alphabetically rather
than
by test score.

I've tried things like t.sort.name and other variations. I also thought
that
I could loop through t and push data to a new array and sort that, but
it
doesn't seem very clean.

My example is more complicated but that is the gist.

Thanks.
Steve O.
http://www.smarkets.net
Ezra Z. (Guest)
on 2005-12-26 23:23
(Received via mailing list)
On Dec 26, 2005, at 11:27 AM, Steve O. wrote:

> t= Testscores.find(:all, :order => "score DESC", :limit => 2)
>
> ...where it would return the records for Jim and Steve....
>
> My question is:
> Is it possible to sort the resulting array "t" by name?

t = t.sort_by{|test| test.student }


That will sort the records in alphabetical order by the student name.
Then you should be able to iterate through them like normal except
they will be in the order you want.

-Ezra


>
> removed_email_address@domain.invalid
> http://lists.rubyonrails.org/mailman/listinfo/rails

-Ezra Z.
WebMaster
Yakima Herald-Republic Newspaper
removed_email_address@domain.invalid
509-577-7732
Steve O. (Guest)
on 2005-12-27 15:20
(Received via mailing list)
Damn Ezra, I'm going to have to make my email signature say "Thanks
Ezra"
because it would save me a lot of typing.

Thanks Ezra.

Steve
This topic is locked and can not be replied to.