理解 validates_linked
根据 Rails 指南,我对 validates_linked 的理解是,它应该确保关联记录在保存之前有效。例如:
class ForumPost < AR:Base
has_many :replies
end
class ForumPostReply < AR:Base
validates_length_of :content, :minimum => 20
end
单元测试:
forum_post = Factory.create(:forum_post)
forum_post.replies.build(:content => 'some content') #content too short, not valid
forum_post.save
forum_post.errors.should be_empty #empty because reply was not expected to be validated
鉴于我没有在 ForumPost 模型中指定 validates_linked :replies,我是否应该预期此保存会失败?它似乎保存得很好,这不是我所期望的,因为我没有指定关联的验证。
因此,如果模型在未指定 validates_linked 的情况下以这种方式运行,那么 validates_linked 会做什么?
My understanding of validates_associated, as per the rails guide, is that it should ensure that an associated record is valid before saving. For example:
class ForumPost < AR:Base
has_many :replies
end
class ForumPostReply < AR:Base
validates_length_of :content, :minimum => 20
end
Unit Test:
forum_post = Factory.create(:forum_post)
forum_post.replies.build(:content => 'some content') #content too short, not valid
forum_post.save
forum_post.errors.should be_empty #empty because reply was not expected to be validated
Should I expect this save to fail given the fact that I didn't specify validates_associated :replies in my ForumPost model? It seems to save just fine which is not what I expected as I had not specified validates associated.
So if the models behave this way without validates_associated specified, then what does validates_associated do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想我会将其移至答案。您说:
“鉴于我没有在 ForumPost 模型中指定
validates_linked :replies
,我是否应该预期此保存会失败?”不,您应该期望它能够保存,因为您没有指定
validates_linked :replies
“它似乎保存得很好,这不是我所期望的,因为我没有指定验证联系。”
它似乎保存得很好,因为它不验证关联,因为您没有指定它。
Figured I would move this to an answer. You say,
"Should I expect this save to fail given the fact that I didn't specify
validates_associated :replies
in my ForumPost model?"No, you should expect it to save because you don't specify
validates_associated :replies
"It seems to save just fine which is not what I expected as I had not specified validates associated."
It seems to save just fine because it isn't validating the associated because you didn't specify it.