在Ruby ActiveRecord模型中级联删除? [英] Cascade delete in Ruby ActiveRecord models?
问题描述
我正在跟踪rubyonrails.org上的截屏视频(创建博客)。
I was following the screencast on rubyonrails.org (creating the blog).
我有以下模型:
comment.rb
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本身可以负责删除相关注释?)?
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? )?
推荐答案
是。在Rails的模型关联上,可以指定:dependent
选项,该选项可以采用以下三种形式之一:
Yes. On a Rails' model association you can specify the :dependent
option, which can take one of the following three forms:
-
:destroy /:destroy_all
通过调用其destroy $ c $销毁关联的对象c>方法
-
:delete /:delete_all
所有关联的对象均被立即销毁,而无需调用其:destroy
方法 -
:nullify
所有关联对象的外键均设置为NULL
而不调用其保存
回调
: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
callbacks
如果您有:has_many X,:through => ;,则忽略
关联已建立。:dependent
选项。 Y
Note that the :dependent
option is ignored if you have a :has_many X, :through => Y
association set up.
因此,在您的示例中,当帖子本身被删除时,您可以选择让该帖子删除所有与其相关的评论,而不调用每个注释的 destroy
方法。看起来像这样:
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:
class Post < ActiveRecord::Base
validates_presence_of :body, :title
has_many :comments, :dependent => :delete_all
end
Rails 4的更新:
在Rails 4中,应该使用:destroy
而不是:destroy_all
。
如果使用:destroy_all
,则会出现异常:
If you use :destroy_all
, you'll get the exception:
:depend选项必须是[:destroy,:delete_all,:nullify,
:restrict_with_error,:restrict_with_exception]之一
The :dependent option must be one of [:destroy, :delete_all, :nullify, :restrict_with_error, :restrict_with_exception]
这篇关于在Ruby ActiveRecord模型中级联删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!