Ruby ActiveRecord 模型中的级联删除?
我正在关注 rubyonrails.org 上的截屏视频(创建博客)。
我有以下模型:
comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
validates_presence_of :body # I added this
end
post.rb
class Post < ActiveRecord::Base
validates_presence_of :body, :title
has_many :comments
end
模型之间的关系工作正常,除了一件事 - 当我删除帖子记录时,我希望 RoR 删除所有相关的评论记录。据我所知,ActiveRecords 是独立于数据库的,因此没有内置方法来创建外键、关系、ON DELETE、ON UPDATE 语句。那么,有什么办法可以做到这一点(也许RoR本身可以删除相关评论?)?
I was following the screencast on rubyonrails.org (creating the blog).
I have following models:
comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
validates_presence_of :body # I added this
end
post.rb
class Post < ActiveRecord::Base
validates_presence_of :body, :title
has_many :comments
end
Relations between models work fine, except for one thing - when I delete a post record, I'd expect RoR to delete all related comment records. I understand that ActiveRecords is database independent, so there's no built-in way to create foreign key, relations, ON DELETE, ON UPDATE statements. So, is there any way to accomplish this (maybe RoR itself could take care of deleting related comments? )?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。在 Rails 的模型关联上,您可以指定
:dependent
选项,该选项可以采用以下三种形式之一::destroy/:destroy_all
关联的对象将与此一起销毁通过调用其destroy
方法来调用对象:delete/:delete_all
所有关联的对象都会立即销毁,而不调用其:destroy
方法:nullify< /code> 所有关联对象的外键均设置为
NULL
,而不调用其save
回调请注意,如果您有以下情况,
:dependent
选项将被忽略a:has_many X, :through =>; Y 协会成立。
因此,对于您的示例,您可以选择让帖子在删除帖子本身时删除所有关联的评论,而不调用每个评论的
destroy
方法。看起来像这样:Rails 4 的更新:
在 Rails 4 中,您应该使用
:destroy
而不是:destroy_all
。如果您使用
:destroy_all
,您将收到异常:Yes. On a Rails' model association you can specify the
:dependent
option, which can take one of the following three forms::destroy/:destroy_all
The associated objects are destroyed alongside this object by calling theirdestroy
method:delete/:delete_all
All associated objects are destroyed immediately without calling their:destroy
method:nullify
All associated objects' foreign keys are set toNULL
without calling theirsave
callbacksNote that the
:dependent
option is ignored if you have a:has_many X, :through => Y
association set up.So for your example you might choose to have a post delete all its associated comments when the post itself is deleted, without calling each comment's
destroy
method. That would look like this:Update for Rails 4:
In Rails 4, you should use
:destroy
instead of:destroy_all
.If you use
:destroy_all
, you'll get the exception: