Reputation: 4369
I have defined three classes:
class Animal < ActiveRecord::Base
end
class Cat < Animal
has_many :toys
end
class Toy
validates_presence_of :cat
belongs_to :cat
end
When I create a toy that should belong to a cat with :
Cat.first.toys << Toy.create!(:name => 'Toy 1')
it throws :
ActiveRecord::RecordInvalid: Validation failed: Cat can't be blank
Upvotes: 1
Views: 225
Reputation: 16011
Cat.first.toys << Toy.create!(:name => 'Toy 1')
The sequence of the code would be executed like the following:
tmp_toy = Toy.create!(:name => 'Toy 1')
Cat.first.toys << tmp_toy
So when you are creating the new toy, you did not provide the required cat, that causes the error.
You could use the following:
Cat.first.toys.create!(:name => 'Toy 1')
Upvotes: 3