如何通过关系访问自引用has_many中的两个关联?

时间:2016-06-26 13:46:34

标签: ruby-on-rails activerecord

如果我有一个关联类,如:

class TranslationAssociation < ActiveRecord::Base

  belongs_to :child, class_name: "Translation"
  belongs_to :translation

这样的课程如下:

class Translation < ActiveRecord::Base

  has_many :translation_associations
  has_many :children, through: :translation_associations

我让孩子们好了。但如果我还是个孩子,我该如何创建一个关系以获得父母?

1 个答案:

答案 0 :(得分:1)

将翻译课程更改为以下代码

class Translation < ActiveRecord::Base

  has_many :translation_associations
  has_many :children, through: :translation_associations
  has_many :parent_associations, class_name:'TranslationAssociation', foreign_key:'child_id'
  has_many :parents, through: :parent_associations, source: :translation

您可以在导轨指南中了解有关轨道关系的更多信息。 http://guides.rubyonrails.org/association_basics.html#has-many-association-reference