型号:
class Factory < ActiveRecord::Base
has_many :factory_workers
has_many :workers, through: :factory_workers
end
class FactoryWorkers < ActiveRecord::Base
belongs_to :factory
belongs_to :worker
before_destroy :union_approves?
private
def union_approves?
errors.add(:proletariat, "is never destroyed!")
false
end
end
class Worker < ActiveRecord::Base
has_many :factory_workers
has_many :factorys, through: :factory_workers
end
如果我尝试通过Factory更新Factory的Workers列表,并导致一些FactoryWorker关联的破坏,我希望调用before_destroy挂钩,但似乎不是这种情况。
实施例
Factory.create(name: 'communist paradise', worker_ids: [1, 2])
Factory.find_by(name: 'commnist paradise').update(worker_ids: [1])
# before_destroy hook is not called, proletariat must riot!
如何在更新记录的关联时确保调用before_destory挂钩?
答案 0 :(得分:1)
找到我需要的东西:ActiveRecord为关联提供了一个before_remove方法,所以我只需要重新调整如下:
class Factory < ActiveRecord::Base
has_and_belongs_to_many :workers, before_remove: :union_approves?
private
def union_approves?
...
end
end