ActiveRecord has_many 关系防止孤立新创建的对象
假设我有一个属于 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为为了使其能够与 new 一起使用,您必须在 after_initialize 中执行此操作:
不过,这似乎有点矫枉过正,因为每次实例化 Comment 时都必须运行它。我想说编写测试以确保默认值设置正确。
I think in order for this to work with
new
you have to do it inafter_initialize
: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.
我会在您的评论模型中添加验证,如下所示:
然后使用以下命令创建新评论:
I would add a validation in your Comment model like so:
Then create new comments using: