Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Many to many relation to self

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
like image 361
Eike Cochu Avatar asked Jan 29 '26 15:01

Eike Cochu


1 Answers

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
like image 196
Nic Nilov Avatar answered Jan 31 '26 05:01

Nic Nilov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!