Association deletion in Rails

Scenes

When deleting a record, it needs to delete a certain type of record associated with it, for example:

class Category < ApplicationRecord
    has_many :blogs
end
复制代码

When deleting a category, all blogs associated with it need to be deleted.

solution

spelling one

class Category < ApplicationRecord
    has_many :blogs, dependent: :destroy
    # or
    # has_many :blogs, dependent: :delete_all
end
复制代码

shortcoming

dependent: :destroyIt is an n+1 operation. When a category needs to be deleted, all blogs belonging to this category will be found out and then deleted, which has performance risks. At this point you can use thedelete_all

spelling two

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

If there are errors, please point them out.

Guess you like

Origin juejin.im/post/7087477261728743461