0
votes

I am trying to set up an ActiveRecord object to model a relationship where a table is self-referencing, parent-to-child, with multiple parents and multiple children possible.

The table itself looks like:

create_table :widget do |t|
  t.string :name                  ,:string     ,:null=>false      ,:limit=>100
  t.string :url                   ,:string     ,:null=>true       ,:limit=>100      
  t.timestamps
end

and the rel table would look like:

create_table "widget_rels" do |t|
  t.integer "parent_id"
  t.integer "child_id"
end

but i'm struggling with what the AR object would define for the relationship.

Seems like 'has_and_belongs_to_many' or 'has_many, :through=>', but not sure how the self-referencing part affects things..

Any guidance much appreciated!

1

1 Answers

0
votes

Not 100% sure it will work, but you could try this:

widget.rb

has_and_belong_to_many :parents, :class_name => "Widget", through: :widget_rels, :foreign_key => 'parent_id'
has_and_belong_to_many :children, :class_name => "Widget", through: :widget_rels, :foreign_key => 'child_id'