我在创建此关联时遇到问题:考虑一个模型“Entry”。我希望条目有很多条目作为父母,我希望条目有许多条目作为孩子。我希望通过一个名为“Association”的模型来实现这种关系,所以这就是我试过的:
迁移:
class CreateAssociations < ActiveRecord::Migration[5.0]
def change
create_table :associations do |t|
t.integer :parent_id
t.integer :child_id
end
end
end
协会模式:
class Association < ApplicationRecord
belongs_to :parent, class_name: 'Entry'
belongs_to :child, class_name: 'Entry'
end
到目前为止它的确有效。但是现在我如何使用它在模型上创建两个多对多关系呢?
class Entry < ApplicationRecord
# has many parent entries of type entry via table associations and child_id
# has many child entries of type entry via table associations and parent_id
end
答案 0 :(得分:3)
这应该有效:
class Entry < ApplicationRecord
has_and_belongs_to_many :parents, class_name: 'Entry', join_table: :associations, foreign_key: :child_id, association_foreign_key: :parent_id
has_and_belongs_to_many :children, class_name: 'Entry', join_table: :associations, foreign_key: :parent_id, association_foreign_key: :child_id
end