association sorting
I have 3 models GrandPa, Pa, Kid
GrandPa => has_many :pas
Pa => has_many kids, :polymorphic => true #dont ask why
When I list GrandPa I would like to开发者_如何学C present the following
1 - GrandPa_Name
2 - List of Pas sorted by the number kids each pa has in descending order
How do I accomplish #2?
Thanks
Try this:
GrandPa.all do |gpa|
p gpa.name
gpa.pas.all(:joins => :kids, :select => "pas.*, count(pas.id) AS kid_count"
:group => :id, :order => "kid_count DESC") do |pa|
p "#{pa.name} : #{pa.kid_count}"
end
end
Use the approach below, if you eager load parents and kids.
GrandPa.all(:include => {:pas => :kids}) do |gpa|
p gpa.name
gpa.pas.sort_by{|pa| pa.kids.size}.reverse_each do |pa|
p "#{pa.name} : #{pa.kids.size}"
pa.kids do |kid|
p kid.name
end
end
end
精彩评论