【问题标题】:Rails - Multiple Relationship FindRails - 多重关系查找
【发布时间】:2011-11-18 15:59:21
【问题描述】:

为了简化我的问题,假设我们有三个模型; 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

【问题讨论】:

    标签: ruby-on-rails activerecord model relationships


    【解决方案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
    

    【讨论】:

    • 好的,谢谢 - 但我需要从它们循环,在循环中我需要有飞机对象,以及用户飞行那架飞机的次数 - 我该怎么做?
    • 太棒了 - 你今天为我回答的第二个问题 :)
    猜你喜欢
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    相关资源
    最近更新 更多