Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails-多关系查找_Ruby On Rails_Activerecord_Model_Relationships - Fatal编程技术网

Ruby on rails Rails-多关系查找

Ruby on rails Rails-多关系查找,ruby-on-rails,activerecord,model,relationships,Ruby On Rails,Activerecord,Model,Relationships,为了简化我的问题,假设我们有三个模型用户,航班和飞机。我想向用户展示一张表格,显示他们驾驶每架飞机的次数 我完全被困在如何做到这一点。。。我能想到的最简单的解决办法就是像这样在飞行中循环 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 e

为了简化我的问题,假设我们有三个模型<代码>用户,
航班
飞机
。我想向用户展示一张表格,显示他们驾驶每架飞机的次数

我完全被困在如何做到这一点。。。我能想到的最简单的解决办法就是像这样在飞行中循环

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 Flight
平面

class Plane < ActiveRecord::Base
  has_many :flights
end
类平面
用户

class User < ActiveRecord::Base
  has_many :flights
end
class用户
使用
分组依据
将用户的航班按飞机分组

@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

使用
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

好的,谢谢-但我需要从他们那里循环,在循环中我需要飞机对象,以及用户驾驶飞机的次数-我怎么能做到?太棒了-你今天为我回答的第二个问题:)好的,谢谢-但我需要从他们那里循环,在循环中我需要飞机对象,还有用户驾驶那架飞机的次数——我怎么能做到?太棒了——你今天为我回答的第二个问题:)