Skip to content

Instantly share code, notes, and snippets.

@phinze
Created September 10, 2009 20:34
Show Gist options
  • Save phinze/184803 to your computer and use it in GitHub Desktop.
Save phinze/184803 to your computer and use it in GitHub Desktop.
## app/models/person.rb
class Person < ActiveRecord::Base
has_many :pets
end
## app/models/pet.rb
class Pet < ActiveRecord::Base
belongs_to :person
end
## GOOD
>> p = Pet.new(:species => 'dog', :name => 'barky')
=> #<Pet id: nil, species: "dog", name: "barky", created_at: nil, updated_at: nil, person_id: nil>
>> p.person = Person.new(:firstname => 'mister', :lastname => 'talky')
=> #<Person id: nil, firstname: "mister", lastname: "talky", created_at: nil, updated_at: nil>
>> p.save!
Person Create (0.2ms) INSERT INTO "people" ("created_at", "updated_at", "lastname", "firstname") VALUES('2009-09-10 20:30:35', '2009-09-10 20:30:35', 'talky', 'mister')
Pet Create (0.1ms) INSERT INTO "pets" ("name", "created_at", "updated_at", "person_id", "species") VALUES('barky', '2009-09-10 20:30:35', '2009-09-10 20:30:35', 4, 'dog')
=> true
>> p.person.pets
Pet Load (0.3ms) SELECT * FROM "pets" WHERE ("pets".person_id = 4)
=> [#<Pet id: 4, species: "dog", name: "barky", created_at: "2009-09-10 20:30:35", updated_at: "2009-09-10 20:30:35", person_id: "4">]
## Now add validates associated... new app/models/person.rb
class Person < ActiveRecord::Base
has_many :pets
validates_associated :pets
end
## BAD
>> p = Pet.new(:species => 'dog', :name => 'barky')
=> #<Pet id: nil, species: "dog", name: "barky", created_at: nil, updated_at: nil, person_id: nil>
>> p.person = Person.new(:firstname => 'mister', :lastname => 'talky')
=> #<Person id: nil, firstname: "mister", lastname: "talky", created_at: nil, updated_at: nil>
>> p.save!
Person Create (0.3ms) INSERT INTO "people" ("created_at", "updated_at", "lastname", "firstname") VALUES('2009-09-10 20:35:33', '2009-09-10 20:35:33', 'talky', 'mister')
Pet Create (0.1ms) INSERT INTO "pets" ("name", "created_at", "updated_at", "person_id", "species") VALUES('barky', '2009-09-10 20:35:33', '2009-09-10 20:35:33', 5, 'dog')
=> true
>> p.person.pets
=> []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment