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:
class CreateAssociations < ActiveRecord::Migration[5.0]
create_table :associations do |t|
class Association < ApplicationRecord
belongs_to :parent, class_name: 'Entry'
belongs_to :child, class_name: 'Entry'
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
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