开发者

association sorting

开发者 https://www.devze.com 2023-01-07 19:48 出处:网络
I have 3 models GrandPa, Pa, Kid GrandPa => has_many :pas Pa => has_many kids, :polymorphic => true #dont ask why

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
0

精彩评论

暂无评论...
验证码 换一张
取 消