Chris
Chris

Reputation: 6246

HABTM Relationship With Self?

Is it possible to have a has and belongs to many relationship in active record that references the same model?

I want to model a sibling type relationship.

class Child < ActiveRecord::Base
  has_and_belongs_to_many :siblings
end

So far I have created a siblings link table:

class CreateSiblings < ActiveRecord::Migration
  def change
    create_table :siblings do |t|
      t.integer :child1_id
      t.integer :child2_id
      t.timestamps
    end
  end
end

But I fear this will lead to me writing ugly code in order to get at the actual instances:

siblings = []
child1.siblings.each do |s|
  siblings << s.child2
end

I would much rather be able to get an array of children by writing:

child1.siblings

I am wondering how my link table and model associations should look to support this?

Feel like I am missing something really obvious.

I am on Rails 3.1. Thanks for any help!

Upvotes: 1

Views: 468

Answers (1)

Ekampp
Ekampp

Reputation: 755

Method 1:

I would simply add a column called something like parent_id.

I would then make an instance method on the model, something like:

def children
  Model.where({ parent_id: id })
end

And if you want the parent you could do something like:

def parent
  Model.where({ id: parent_id }).first
end

And you can then collect the siblings like this:

def siblings
  parent.children.reject{ |r| r == self }
end

Method 2:

You could also try with the belongs_to relation, something like:

belongs_to :parent, class_name: "Model", foreign_key: :parent_id

But I'm not 100 percent sure about this method. You might have to tweak that a bit before it works.

I hope it helps :)

\\ Emil

Upvotes: 4

Related Questions