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
The sequence of the code would be executed like the following:
So when you are creating the new toy, you did not provide the required cat, that causes the error.
You could use the following: