Rails 3.x — Self-referential has_many :through Parent<->Child relationship modelling

Stamped: 01 Sep 2010 | Show comments


Srsly, that's more of an SEO title than anything, because damnit, I know how the hell it works at an SQL level and it was frustrating to get working in Rails because of syntax, namely :class_name => :object, when it should be :class_name => "object". I hope someone finds this useful, because when it comes to rails 3 there's not too much stuff that's recent.

Get to the point, show me the goods

rails new confusingTitleProject
cd confusingTitleProject
rails g model Person name:string
rails g model PersonRelationship parent_id:integer child_id:integer
class PersonRelationship < ActiveRecord::Base
  belongs_to :parent, :class_name => "Person"
  belongs_to :child, :class_name => "Person"

class Person < ActiveRecord::Base
  validates_presence_of :first_name, :last_name

  has_many     :parent_child_relationships,
               :class_name            => "PersonRelationship",
               :foreign_key           => :child_id,
               :dependent             => :destroy
  has_many     :parents,
               :through               => :parent_child_relationships,
               :source                => :parent

  has_many     :child_parent_relationships,
               :class_name            => "PersonRelationship",
               :foreign_key           => :parent_id,
               :dependent             => :destroy
  has_many     :children,
               :through               => :child_parent_relationships,
               :source                => :child

Then, as an example, you can do the following to add a parent:

a = Person.new; b = Person.new
b.parents = [a]
tags: rails, self join, has_many through, habtm
recent entries
Rails — A faster way for next and previous links on a post, article, or any model
The awkward things Siri says
Node.js — Getting oAuth Up and Running Using Express.js and Mongoose
Node.js — Getting oAuth Up and Running Using Express.js, Railway.js and Mongoose
Migrating from Rails 3.1 RC4 to RC5 using Heroku's Cedar Stack (also compass, unicorn, and sendgrid)
Random Freeze Fix for GTX 460 in 10.6 (osx86)
Wasted on Steam - an analytic tool for the Steam platform
Rails 3.1 — SQL logging to STDOUT during testing (with rspec, test::unit, or cucumber)
Rails 3.1 — Using ERB/HAML/etc within a Coffeescript JS file
Rails 3.1 — 'load_missing_contant': Expected ... to define ... (LoadError)
View the entire archive of articles