Skip to content

Instantly share code, notes, and snippets.

@latentflip
Created June 3, 2010 12:53
Show Gist options
  • Save latentflip/423842 to your computer and use it in GitHub Desktop.
Save latentflip/423842 to your computer and use it in GitHub Desktop.
#given the following models---------------------------
class Parent
has_many :children
end
class Child
belongs_to :parent #column: parent_id in the db
end
#Set up some relationships-----------------------------
#Jimmy has a dad:
dad = Parent.new #let's say he gets id=1
jimmy = Child.new
jimmy.parent_id = dad.id #stores '1' parent_id column
jimmy.save!
#Jonny is an orphan :(
jonny = Child.new
#If want to access the parent id of a child--------------
#We can either do child.parent.id, or child.parent_id
#This works find for Jimmy
jimmy.parent.id #=>1 (yup)
jimmy.parent_id #=>1 (yup)
#but if we try this on Jonny (who has no parent)
jonny.parent_id #=>nil (as expected)
jonny.parent.id #=>4 <<(wtf?!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment