gadys
December 13, 2007, 3:20pm
1
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 => …
gadys
December 13, 2007, 3:53pm
2
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]
gadys
December 13, 2007, 4:21pm
3
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
gadys
December 13, 2007, 4:33pm
4
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
gadys
December 13, 2007, 5:45pm
5
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]
gadys
December 14, 2007, 4:31am
6
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]