如何在一个自引用的has_many through关系中访问两个关联



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

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

我得到孩子们很好。但如果我是一个孩子,我该如何与父母建立关系呢?

将Translation类更改为以下代码

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

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

最新更新