我正在关注 ruby​​onrails.org 上的截屏视频(创建博客)。

我有以下型号:

评论.rb

class Comment < ActiveRecord::Base
    belongs_to :post
    validates_presence_of :body # I added this
end

后rb

class Post < ActiveRecord::Base
    validates_presence_of :body, :title
    has_many :comments
end

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

有帮助吗?

解决方案

是的。在 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

Rails 4 更新:

在 Rails 4 中,您应该使用 :destroy 代替 :destroy_all.

如果你使用 :destroy_all, ,你会得到异常:

:依赖的选项必须是[:destion,:delete_all,:nullify,:drelotct_with_error,:dreloct_with_exception

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top