Md. Kazim Zaidi wrote: > Hello everyone, > This is my first post to this list, so kindly remind me if I do > something wrong. :-P > > 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?
Use validates_presence_of :author instead. Currently you also have to do the build like u.books.build(:title => 'The Comedy of Errors', :author => u) -- Rails Wheels - Find Plugins, List & Sell Plugins - http://railswheels.com --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---

