Rails - 多重关系查找

时间:2011-11-18 15:59:22

标签: ruby-on-rails activerecord model relationships

为了简化我的问题,我们假设我们有三个模型; userflightplane。我想向用户展示一张桌子,告诉他们飞过每架飞机的次数。

我完全被困在如何实现这个目标......我能想到的最简单的解决方案是像这样循环飞行......

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 个答案:

答案 0 :(得分: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