Hello everyone,
This is my first post to this list, so kindly remind me if I do
something wrong.
When parent objects are saved, all the new children are saved.
However, when the child objects validate themselves, they fail because
the foreign key is nil.
Domain logic in my application requires complex validations, which
will just fail because the associated object is nil. I’m trying to
illustrate using an over-simplified example:
(also pasted at http://pastie.org/295133)
*** Schema ***
User(id, name, age)
Book(id, title, author_id)
*** app/models/user.rb ***
class User < ActiveRecord::Base
has_many :books, :foreign_key => ‘author_id’
end
*** app/models/book.rb ***
class Book < ActiveRecord::Base
belongs_to :author, :class_name => ‘User’, :foreign_key =>
‘author_id’
validates_presence_of :author_id
end
*** ./script/console ***
u = User.new(:name => ‘Shakespeare’, :age => 444)
u.books.build(:title => ‘The Comedy of Errors’)
u.save!
ActiveRecord::RecordInvalid: Validation failed: Books is invalid
Bad Solution: Remove validates_presence_of :author_id from Book model.
This makes the model unsafe, but things work.
I hope I’m not following the best practices and somebody enlightens
me. But if this is meant to be in this way, then how do I implement my
validations on a Book?
Any comment/suggestion/hint appreciated.