首页 > 解决方案 > 多个 Has_Many 与相同模型但不同列表的关系

问题描述

我正在努力建立一个一对多的关系,顺便说一下,父对象与子对象有3种不同的关系。孩子只能与父母处于这 3 种关系中的一种。

我有一种感觉,我把它混合了一点,会很好,如果有人可以为这个话题带来一些启发,那么建立这些关系的最佳实践方法是什么。我对rails比较陌生。干杯

我的迁移

add_reference :child_elements, :child_list_a, foreign_key: { to_table: :parent_elements }

add_reference :child_elements, :child_list_b, foreign_key: { to_table: :parent_elements }

add_reference :child_elements, :child_list_c, foreign_key: { to_table: :parent_elements }

课程:

Child:
belongs_to :child_list_a, class_name: "ParentElement"
belongs_to :child_list_b, class_name: "ParentElement"
belongs_to :child_list_c, class_name: "ParentElement"


Parent:

has_many :child_elements_a, inverse_of: "child_list_a"
has_many :child_elements_b, inverse_of: "child_list_b"
has_many :child_elements_c, inverse_of: "child_list_c"

标签: rubyactiverecordruby-on-rails-5rails-activerecord

解决方案


推荐阅读