How to validate that a parent object has a valid child object (Rails)
Let's say I have an ActiveRecord model called Book that has a has_many association with a model Pages.
class Book < ActiveRecord::Base
has_many :pages
end
I'd like to know if there is an established method of ensuring that a Book object cannot be saved to the database without having at least one valid Page object associated with it. My goal is not to test the presence of an association, but to validate that a parent object indeed has a valid child object. Does this make sense? Is this 开发者_开发技巧actually a case of testing an association? I'm familiar with the "validates_associated" method, but this validation will not fail if the association hasn't been assigned, but how do I ensure that there is a valid object on the other side of the association?
From the Rails 2.3.2 documentation for validates_associated
:
NOTE: This validation will not fail if the association hasn’t been assigned. If you want to ensure that the association is both present and guaranteed to be valid, you also need to use validates_presence_of.
精彩评论