Sorting the children of an object

Hi
another quick question.
i have a relationship “areas has_many elements” (elements acts_as_list)
i want to retrive those elements ordered by element.position

elements = area.elements
elements.each do |element|

is there a quick and elegent way to it (like area.elements.orderby)
or is an SQL query a must.

like :
Element.find(:all, condition => …, order => …

http://www.ruby-doc.org/core/classes/Array.html#M002208
Something like:
elements.sort{ |x,y| x.position <=> y.position }

On Dec 13, 3:20 pm, Gady S. [email protected]

You can actually do a find like such:

elements = area.elements.find(:all, :order => “name”)

and it will automatically scope only to elements in the area. Still a
‘query’, but a very simple one.

Michael

thanks.
these are good solutions.
which one is better optimized ?
Michael B. wrote:

You can actually do a find like such:

elements = area.elements.find(:all, :order => “name”)

and it will automatically scope only to elements in the area. Still a
‘query’, but a very simple one.

Michael

you can also sort through the association

has_many :elements, :order => :position

so area.elements will always be sorted.

On Dec 13, 10:33 am, Gady S. [email protected]

They are negligibly different in terms of efficiency. The
has_many :elements, :order => :name has a simplicity that I like, I
would go with that one.

Michael B.
[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs