Single Table HABTM with Rails 3

I'm building a user model that keeps track of your parents and any children you should have. The acts_as_tree plugin
wouldn't have worked because it wouldn't allow for a parent to have many children. What's needed is a HABTM relationship. It's a quite simple relationship except for the :association_foreign_key option not being listed in the docs. Anyways I found some people discussing it here.


class User < ActiveRecord::Base
  has_and_belongs_to_many :parents,  :class_name => "User", :join_table => "parents_children", :foreign_key => "child_id", :association_foreign_key => "parent_id"
  has_and_belongs_to_many :children, :class_name => "User", :join_table => "parents_children", :foreign_key => "parent_id" , :association_foreign_key => "child_id"
end
describe User do
  it "should have 0 children" do
    User.new.should have(0).children
  end
  it "should have 0 parents" do
    User.new.should have(0).parents
  end
  it "should have 1 child" do
    parent = User.new
    parent.children << User.new
    parent.should have(1).children
  end
  it "should have 0 parents" do
    child = User.new
    child.parents << User.new
    child.should have(1).parents
  end
end

Leave a Reply

You must be logged in to post a comment.