【发布时间】:2016-12-02 22:29:11
【问题描述】:
编辑:这可能有助于解决我的问题......
有没有办法通过:关联进行“级联”?例如,如果我们用骨头歌曲:“脚骨连接到踝骨,踝骨连接到腿骨,腿骨连接到髋骨......”我不想说脚有很多髋骨,因为这并不完全准确。我也不想说脚有很多髋骨穿过腿骨(因为它也需要穿过脚踝)。相反,脚有很多臀部穿过脚踝,穿过腿。脚连接到脚踝,然后将 foot_ankle 组件连接到腿,然后整个 foot_ankle_leg 组件最终连接到臀部。所以一只脚可以有很多臀部,但这只脚并不是孤立地属于一个臀部,这种关联仅作为特定 foot_ankle_leg 组件的一部分存在。
为了表示这样的事情,我在通过桌子设置中间以“携带”脚/脚踝/腿连接到臀部时是否正确? (即 a_b_c_d_e 表代表类似于“最终”foot_ankle_leg_hip 装配的东西)
原始问题:有几个模型与各种介入的多对多 :through 表结合在一起。未使用 HABTM,因为这些直通表包含其他属性。
这是它如何组合在一起的图像,绿色框是多对多连接表。为简洁起见,重命名为字母
这是结构的编码方式
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
每当我尝试从控制台中的父对象访问嵌套的子对象时,例如A.first.a_b_c_ds,它都会返回
#<ABCD::ActiveRecord_Associations_CollectionProxy:0x26ca578>。
这是我应该看到的吗?我是否需要直接与 CollectionProxy 交互而不是查看“通常”的记录输出?如果是这样,那是我需要学习的新事物:)
在读出中,我还注意到它试图在直通表中查找父 ID,而不是关联的“子”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 显然不会出现在表 ABCD 中。但是ab_id 在那里, 与a_id 相关联。如果我正确地阅读了 rails-guide,那么如果我设置得当,rails 应该足够聪明,可以做出区分。
知道我在哪里走错了吗?
类名不一定按字母顺序排列。例如,Wrapping、Package、Object、WrappingPackage、WrappingPacakgeObject。但由于我使用命名多对多 through: 表,所以我的理解是表名应该无关紧要。它仅在使用 has_many_and_belongs_to 连接表时才起作用。但那是我离开的地方吗?
感谢您的帮助!如果您需要更多 sn-ps,请告诉我!
【问题讨论】:
-
你的例子:
A.first.a_b_c_ds好像不对,A 中没有a_b_c_ds关联。 -
啊,好吧!所以如果我没听错的话,关联不会像类继承那样自动堆叠或级联?关联必须在“数据链”本身上下明确定义?
标签: ruby-on-rails activerecord collections many-to-many has-many-through