在同一模型上使用许多has_one关系

时间:2015-03-06 06:45:19

标签: ruby-on-rails associations

我有这样的模特匹配:

class Match < ActiveRecord::Base
  belongs_to :match, foreign_key: 'parent'
  belongs_to :match, foreign_key: 'child_left'
  belongs_to :match, foreign_key: 'child_right'
end

许多比赛代表一棵树。

我想设置外键使用Match.first.child_left返回对象匹配而不只是表示id的整数。

更好,我可以在这种情况下使用has_one关系吗?因为它使用每个模型匹配但使用不同的foreign_key。

更好的是,我可以肯定的是,当我将child_left放入匹配项时,它会将子项匹配的父属性设置为db,还是应该使用ruby?

1 个答案:

答案 0 :(得分:2)

尝试:

class Match < ActiveRecord::Base
  belongs_to :parent, class_name: 'Match'
  belongs_to :child_left, class_name: 'Match'
  belongs_to :child_right, class_name: 'Match'
end

您的matches表格应包含整数字段parent_idchild_left_idchild_right_id。您应该能够像这样使用它:

Match.first.child_left
相关问题