问题
I am having problems creating this association: Consider a model "Entry". I want entries to have many entries as parents and I want entries to have many entries as children. I want to realize this relation via a model I called "Association", so here is what I tried:
Migration:
class CreateAssociations < ActiveRecord::Migration[5.0]
def change
create_table :associations do |t|
t.integer :parent_id
t.integer :child_id
end
end
end
Association model:
class Association < ApplicationRecord
belongs_to :parent, class_name: 'Entry'
belongs_to :child, class_name: 'Entry'
end
so far it works. But now how do I use this to create two many-to-many relations on a model to itself?
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
回答1:
This should work:
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
来源:https://stackoverflow.com/questions/38577147/rails-many-to-many-relation-to-self