理解 validates_linked

发布于 2024-11-08 11:30:16 字数 684 浏览 0 评论 0原文

根据 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜`诱少女 2024-11-15 11:30:16

我想我会将其移至答案。您说:

“鉴于我没有在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文