Ordering Results returned by has_many relationship


#1

Noob Question 31,265,232

if I’m searching on an object, say order, that has many “order_lines”
and I want to display order lines by Quantity ( an attribute of the
order_lines ) descending
how could I do that without having to do a find() with :order, but
something like;

Order.order_lines.each do |ol|

how can I determine the field and the way I order the results?

Thanks in advance,
Randal the Newbie


#2

Nevermind, I’m just a little slow. I was puttin in the ORDER class, how
to order the order_lines, and didn’t realise I could do

has_many :order_lines, :order => “quantity DESC”

problem solved, and now archieved for future noobs :slight_smile:

Randal S. wrote:

Noob Question 31,265,232

if I’m searching on an object, say order, that has many “order_lines”
and I want to display order lines by Quantity ( an attribute of the
order_lines ) descending
how could I do that without having to do a find() with :order, but
something like;

Order.order_lines.each do |ol|

how can I determine the field and the way I order the results?

Thanks in advance,
Randal the Newbie


#3

On May 2, 2006, at 04:28 PM, Randal S. wrote:

how can I determine the field and the way I order the results?

class Order < ActiveRecord::Base
has_many :order_lines, :order => “order_lines.quantity”
end

More info: <http://rails.rubyonrails.org/classes/ActiveRecord/
Associations/ClassMethods.html#M000530>

-Brian