ActiveRecord has_many 关系防止孤立新创建的对象

发布于 2024-09-28 03:55:59 字数 281 浏览 1 评论 0原文

假设我有一个属于 Post 模型的 Comment 模型。

我想让它创建一个新的 Comment 实例(无论是通过 new、create、find_or_create_by_x 等)都会失败(最好引发异常),除非立即设置 Post(通过将其作为参数传递或通过创建评论时始终引用帖子,例如 post.comments.new 或 post.comments.create)。

我想这样做是因为我想在评论对象中设置一些基于帖子的默认值...因此帖子引用需要立即有效。

实现这一目标的最佳方法是什么?谢谢。

Suppose I have an Comment model that belongs_to a Post model.

I want to make it so that creation of a new Comment instance (whether by new, create, find_or_create_by_x, etc.) will fail (preferably raise an exception) unless the Post is set immediately (either by passing it in as a parameter or by always referencing the post when creating a comment, e.g. post.comments.new or post.comments.create).

I want to do this because I want to set some default values in the comment object which are based on the post...so the post reference needs to be immediately valid.

What is the best way to accomplish this? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

平生欢 2024-10-05 03:55:59

我认为为了使其能够与 new 一起使用,您必须在 after_initialize 中执行此操作:

def after_initialize
  raise "no Post" unless post
end

不过,这似乎有点矫枉过正,因为每次实例化 Comment 时都必须运行它。我想说编写测试以确保默认值设置正确。

I think in order for this to work with new you have to do it in after_initialize:

def after_initialize
  raise "no Post" unless post
end

Seems like overkill though, since that has to run every time a Comment is instantiated. I'd say write tests that ensure the defaults are being set appropriately.

一梦等七年七年为一梦 2024-10-05 03:55:59

我会在您的评论模型中添加验证,如下所示:

class Comment < ActiveRecord::Base
  validates_presence_of :post_id
end

然后使用以下命令创建新评论:

@post = Post.find(params[:post_id])

@post.comments.create(params[:comment])

I would add a validation in your Comment model like so:

class Comment < ActiveRecord::Base
  validates_presence_of :post_id
end

Then create new comments using:

@post = Post.find(params[:post_id])

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