轨。同一模型与许多父母的关联

时间:2018-05-31 10:37:10

标签: ruby-on-rails activerecord associations

我坚持这一点。我有一个模型Position,我需要设置一个关联,其中一个位置可以是compounded position(具有相关位置)和ingredient position(具有父级位置)时间。

所以我创建了一个包含related_positions:copmound_id的表格:ingredient_id

要明确我需要的输出:

related_positions

compound_id | ingredient_id |

pos_1 | POS_2

pos_1 | pos_3

pos_1 | pos_4

pos_5 | POS_2

pos_5 | pos_6

pos_5 | pos_7

pos_1.ingredients = [pos_2,pos_3,pos_4]

pos_5.ingredients = [pos_2,pos_6,pos_7]

pos_2.compounds = [pos_1,pos_5]

可能有点self join但有多个父母

更新:

我发现了How to model a many self-referential relationship with many parents?。哪个非常接近。但我仍然无法让它发挥作用

3 个答案:

答案 0 :(得分:1)

根据描述,共享关联可以是下面提到的内容:

class Position

 has_many :related_positions, class_name: "RelatedPosition", foreign_key: "ingredient_id", :source => :relate_position
 has_many :compounds, class_name: "RelatedPosition", foreign_key: "compound_id", :source => :compound_position
end


class RelatedPosition
 belongs_to :relate_position, class_name: "Position"
 belongs_to :compound_position, class_name: "Position"
end

答案 1 :(得分:0)

看起来你想要做的是自我引用 像这样的东西可能会起作用

class Position
  has_many :children, class_name: 'Position', foreign_key: 'parent_id'
  belongs_to :parent, class_name: 'Position'
end

答案 2 :(得分:0)

感谢帖子http://blog.hasmanythrough.com/2007/10/30/self-referential-has-many-through我得到了我需要的东西。

所以,如果有人有类似的案例,这是我的解决方案:

class Position < ApplicationRecord
  has_many :parents, class_name: 'RelatedPosition', foreign_key: 'ingredient_id', dependent: :destroy
  has_many :children, class_name: 'RelatedPosition', foreign_key: 'compound_id', dependent: :destroy
  has_many :compounds, through: :parents
  has_many :ingredients, through: :children
end

class RelatedPosition < ApplicationRecord
  belongs_to :ingredient, class_name: 'Position'
  belongs_to :compound, class_name: 'Position'
end