views:

149

answers:

2

In ruby on rails how do I find the top 3 records of my table called notices ordered by a particular field, in my case I want to order by the position field which is an integer.

so my notices table looks like this

any help would be greatly appreciated, thanks

+2  A: 

You'd do something like:

Notice.find(:all,:order => "position", :limit => 3)

That would bring the 3 first records ordered by position (in this example, positions 1,2,3 or the first lesser ones. You can change the order value to "position DESC" if you want positions 20,19,18, for example).

Good luck!

Yaraher
thanks yaraher, your answer worked but i gave the correct answer to eimantas, as you don't need the 'ASC' part.
conspirisi
No worries. Be sure to note that you will need to specify either ASC or DESC when working with some more complex queries, so it's always nice to know it can be there.
Yaraher
you shouldn't specify ASC, ever. Its implied by the order by clause.
Omar Qureshi
You are both right Omar and conspirisi. I've updated my answer to show it properly.
Yaraher
+4  A: 

Considering you have Notice ActiveRecord class, this should do: Notice.find(:all, :limit => 3, :order => 'particularField')

Eimantas