Displaying 1 result from an estimated 1 matches for "sorted_parents".
2006 Mar 21
5
Order records based on number of children
...the folllowing:
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
end
Simple has_many relationship. Is there any way to order the results of
a Parent.find_all by the number of children the parent has? I can
sort with
sorted_parents = Parent.find_all.sort {|a,b| b.children.length
<=> a.children.length}
but that''s extremely slow since it needs to iterate over every Parent
and select all of the children for each parent. Is there a faster,
more "Rails" method of getting the same result?
--
Ryan