Rails中的关联删除

485 阅读1分钟

场景

当删除某条记录时,需要将与它关联的某类记录删除,例:

class Category < ApplicationRecord
    has_many :blogs
end

当删除一种分类的时候,需要将其下关联的所有博客删除。

解决方案

写法一

class Category < ApplicationRecord
    has_many :blogs, dependent: :destroy
    # or
    # has_many :blogs, dependent: :delete_all
end

缺点

dependent: :destroy是一个n+1操作,当需要删除一个分类时,会将所属于这个分类的所有blog查出,然后删除,有性能隐患。此时可以使用注释中的delete_all

写法二

class Category < ApplicationRecord 
    def before_destroy 
        self.blogs.destroy_all # 此处n+1,可使用delete_all
    end
end

如有错误,还望指出。