有模型:member(id,project_id,user_id(,project(id(,user(id(,somemodel(id,project_id,user_id(。
-
成员belongs_to :p roject, belongs_to :用户
-
somemodel belongs_to :p roject, belongs_to :user
模型,以便也删除某个模型(与该成员project_id和user_id相同(。怎么做?
为此,我希望将has_many :somemodels, dependent: :destroy
添加到成员中,但我不知道在成员类中给has_many :somemodels
正确的参数。 has_many :somemodels, dependent: :destroy
单独不起作用,因为它尝试通过 somemodels 表中不存在的member_id搜索某个模型,因此会发生no column
错误。
添加到会员的合适has_many :somemodels ...
是什么?
另一种方法是为此特定关系创建一个:through
关联,然后将该关联设置为 dependent: :destroy
。我认为它的结构是这样的:
class Member < ActiveRecord::Base
belongs_to :user
belongs_to :project
has_many :some_models, ->(member) { where(user_id: member.user_id) },
through: :project,
dependent: :destroy
end
我还没有测试过它,但据我所知,它似乎是正确的。
我认为您应该为Member
模型添加一个after_destroy回调:
# In member model
class Member < ApplicationRecord
after_destroy :also_destroy_somemodel
...
def also_destroy_somemodel
# Fast, use in case somemodel dont have any callbacks
Somemodel.where(project_id: project_id, user_id: user_id).delete_all
# Or
# Slow, use in case somemodel has callback(s)
# Somemodel.where(project_id: project_id, user_id: user_id).each &:destroy
end
end
希望对您有所帮助。