如何使用has_many获取嵌套记录:通过关联?

时间:2018-03-27 02:08:34

标签: ruby-on-rails join associations

class Manager < ApplicationRecord
  has_many :bands
end

class Band < ApplicationRecord
  belongs_to :manager
  has_many :member_bands
  has_many :members, through: :member_bands
end

class Member < ApplicationRecord
  has_many :member_bands
  has_many :bands, through: :member_bands
end

class MemberBand < ApplicationRecord
  belongs_to :member
  belongs_to :band
end

我最终要做的是让所有会员为特定经理。

我觉得我需要做一些连接,但是无法确定这一点。

我已经尝试了manager.bands.joins(:members),但我只获得了多个bands而没有成员。

我现在正在与多个循环一起攻击这个:

manager.bands.each do |band|
  band.members.each do |member|
    ##
  end
end

那么,我怎样才能获得与给定members相关联的所有manager(通过bands连接的人)?

1 个答案:

答案 0 :(得分:2)

根据您的关联,您应该只需添加

irb(main):003:0> Manager.first.members
  Manager Load (0.2ms)  SELECT  "managers".* FROM "managers" ORDER BY "managers"."id" ASC LIMIT $1  [["LIMIT", 1]]
  Member Load (0.6ms)  SELECT  "members".* FROM "members" INNER JOIN "member_bands" ON "members"."id" = "member_bands"."member_id" INNER JOIN "bands" ON "member_bands"."band_id" = "bands"."id" WHERE "bands"."manager_id" = $1 LIMIT $2  [["manager_id", 1], ["LIMIT", 11]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Member id: 1>, #<Member id: 2>, #<Member id: 3>, #<Member id: 5>, #<Member id: 6>, #<Member id: 7>]>

给你的经理。

{{1}}