Ruby ActiveRecord模型中的级联删除?

Jak*_*édl 50 ruby-on-rails database-relations rails-activerecord

我正在关注rubyonrails.org上的截屏视频(创建博客).

我有以下型号:

comment.rb

class Comment < ActiveRecord::Base
    belongs_to :post
    validates_presence_of :body # I added this
end
Run Code Online (Sandbox Code Playgroud)

post.rb

class Post < ActiveRecord::Base
    validates_presence_of :body, :title
    has_many :comments
end
Run Code Online (Sandbox Code Playgroud)

模型之间的关系工作正常,除了一件事 - 当我删除帖子记录时,我希望RoR删除所有相关的评论记录.我知道ActiveRecords是独立于数据库的,所以没有内置的方法来创建外键,关系,ON DELETE,ON UPDATE语句.那么,有没有办法实现这一点(也许RoR本身可以处理删除相关的评论?)?

Joh*_*ley 87

是.在Rails的模型关联上,您可以指定:dependent选项,该选项可以采用以下三种形式之一:

  • :destroy/:destroy_all通过调用它们的destroy方法,相关对象将与此对象一起销毁
  • :delete/:delete_all无需调用:destroy方法即可立即销毁所有关联对象
  • :nullify所有关联对象的外键都设置为NULL不调用其save回调

请注意,:dependent如果您:has_many X, :through => Y设置了关联,则会忽略该选项.

因此,对于您的示例,您可以选择在删除帖子本身时删除所有关联的注释,而不调用每个注释的destroy方法.这看起来像这样:

class Post < ActiveRecord::Base
  validates_presence_of :body, :title
  has_many :comments, :dependent => :delete_all
end
Run Code Online (Sandbox Code Playgroud)

Rails 4的更新:

在Rails 4中,你应该使用:destroy而不是:destroy_all.

如果您使用:destroy_all,您将获得例外:

:dependent选项必须是[:destroy,:delete_all,:nullify,:restrict_with_error,:restrict_with_exception]之一

  • 至少从rails 4开始,:destroy_all不是一个选项.使用:销毁. (7认同)
  • 谢谢!找到你的答案有帮助.小注::dependent选项的值可以是:destroy,:delete_all或:nullify. (2认同)
  • 在Rails 4中,你应该使用`:destroy`而不是`:destroy_all`来自rails logs:`:dependent选项必须是[:destroy,:delete_all,:nullify,:restrict_with_error,:restrict_with_exception]之一. (2认同)