开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜