Skip to content

Instantly share code, notes, and snippets.

@mutuelinvestor
Created November 29, 2011 18:01
Show Gist options
  • Save mutuelinvestor/1405739 to your computer and use it in GitHub Desktop.
Save mutuelinvestor/1405739 to your computer and use it in GitHub Desktop.
#Modeling Parent Child Relationships
rails new confusingTitleProject
cd confusingTitleProject
rails g model Person name:string
rails g model PersonRelationship parent_id:integer child_id:integer
#App/Models/PersonRelationship.rb
class PersonRelationship < ActiveRecord::Base
belongs_to :parent, :class_name => "Person"
belongs_to :child, :class_name => "Person"
end
#App/Models/Person.rb
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
end
#As an example
a = Person.new; b = Person.new
b.parents = [a]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment