无法访问嵌套的 many-to-many has_many:通过来自 parent object 的关联

Cannot access nested many-to-many has_many :through associations from parent object

编辑:这可能有助于解决我的问题……

有没有办法 "cascading" 通过:协会?例如,如果我们用骨骼歌曲来表示: "The foot bone is connected to the ankle bone, the ankle bone's connected to the leg bone, the leg bone's connected to the hip bone..." 我不想说脚部 has_many 髋骨,因为那并不完全准确。我也不想说脚 has_many 髋骨穿过腿骨(因为它也需要穿过脚踝)。不,相反,脚 has_many 穿过穿过腿的脚踝。脚连接到脚踝,然后 foot_ankle 组件连接到腿,然后整个 foot_ankle_leg 组件最终连接到臀部。所以一只脚可以有多个臀部,但脚并不单独属于一个臀部,这种关联仅作为特定 foot_ankle_leg 组件的一部分存在。

为了表示这样的东西,我在设置从 table 到 "carry" 到 foot/ankle/leg 到臀部的连接时是否正确? (即 a_b_c_d_e table 代表类似于 "final" foot_ankle_leg_hip 组件的东西)


原始问题:有几个模型与各种干预 many-to-many :through tables 结合在一起。不使用 HABTM,因为这些 tables 包含额外的属性。

这是它如何组合在一起的图像,绿色框是 many-to-many 连接 table。为了简洁起见,重命名为字母

结构的编码方式如下

class A < ApplicationRecord
  has_many :a_bs
  has_many :bs, through: :a_b
...
end

class B < ApplicationRecord
  has_many :a_bs,
  has_many :as, through: :a_b
...
end

class AB < ApplicationRecord
  belongs_to :a
  belongs_to :b
  has_many :a_b_c_ds
  has_many :c_ds, through: :a_b_c_d
...
end

class C < ApplicationRecord
  has_many :c_ds
  has_many :ds, through: :c_d
...
end

class D < ApplicationRecord
  has_many :c_ds
  has_many :cs, through: :c_d
...
end

class CD < ApplicationRecord
  belongs_to :c
  belongs_to :d
  has_many :a_b_c_ds
  has_many :a_bs, through: :a_b_c_d
...
end

class ABCD < ApplicationRecord
  belongs_to :a_b
  belongs_to :c_d
  has_many :a_b_c_d_es
  has_many :es, through: :a_b_c_d_e
...
end

class E < ApplicationRecord
  has_many :a_b_c_d_es
  has_many :a_b_c_ds, through: :a_b_c_d_e
...
end

class ABCDE < ApplicationRecord
  belongs_to :a_b_c_d
  belongs_to :e
...
end

每当我尝试从控制台中的 parent object 访问嵌套的 children 时,如 A.first.a_b_c_ds,它 returns

#<ABCD::ActiveRecord_Associations_CollectionProxy:0x26ca578>

这是我应该看到的吗?我是否需要直接与该 CollectionProxy 交互而不是查看 "usual" 记录输出?如果是这样,那是我需要了解的新事物:)

在 read-out 中,我还注意到它试图在直通 table 中查找 parent 的 ID,而不是关联的 "child" ID。

ABCD Load (0.3ms)  SELECT "a_b_c_ds".* FROM "a_b_c_d" WHERE "a_b_c_d"."a_id" = ?  [["a_id", 1]]

现在,很明显,a_id 不会出现在 table ABCD 中。但是 ab_id 在那里,a_id 相关联。如果我正确阅读 rails-guide,rails 应该足够聪明,可以在我正确设置它的情况下做出区分。

知道我哪里走错了吗?

class 名称不一定按字母顺序排列。例如,Wrapping、Package、Object、WrappingPackage、WrappingPacakgeObject。但是由于我使用命名 many-to-many through: tables,所以我的理解是 table 名称无关紧要。它只有在使用 has_many_and_belongs_ 加入 table 时才会发挥作用。但那是我离开的地方吗?

感谢您的帮助!如果您需要更多片段,请告诉我!

每个 belongs_to 或 has_many 调用都会在 class 的所有实例中创建一个关联方法。

所以当你这样做时:

class A
    has_many bs
end

class B
    has_many cs
end

然后您基本上将方法 bs 添加到 A 的所有实例。 A中没有方法cs,也没有涉及其他魔法。