2011-11-18 50 views
1

爲了簡化我的問題,假設我們有三個模型; user,flightplane。我想向使用者展示他們飛過的每架飛機多少次。Rails - 多關係查找

我完全被卡住就如何實現這一目標?最簡單的解決方案,我能想到的就是通過像這樣的航班循環...

flown_planes = {} 

@user.flights.each do |f| 
    if flown_planes[f.plane.id] 
    flown_planes[f.plane.id] += 1 
    else 
    flown_planes[f.plane.id] = 1 
    end 
end 

我可以以某種方式使用.find.count爲了達成這個?我確信有比上面更清潔的方式。請看下面的關係。


飛行

class Flight < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :plane 
end 

平面

class Plane < ActiveRecord::Base 
    has_many :flights 
end 

用戶

class User < ActiveRecord::Base 
    has_many :flights 
end 

回答

1

使用group_by來將飛機的飛行分組!

@user.flights.group_by(&:plane_id) 

這應該爲你做,...

//迭代...

@user.flights.group_by(&:plane_id).each do |plane_id, flights| 
    plane = Plane.find(plane_id) # gives you the plain object so you can fetch the plane name/identification,... whatever you need 
    flights.count # gives you count of flights in the plane 
    flights.each do |flight| 
      # do anything if you want with each of the flights the user had... 
    end 
end 
+0

好感謝 - 但我需要循環的他們,在環我需要有飛機對象,以及用戶乘坐飛機的次數 - 我該怎麼做? –

+0

查看帖子更新 – davidb

+0

精彩 - 你今天回答的第二個問題:) –