class Actor < ActiveRecord::Base
has_and_belongs_to_many :movies
before_destroy :remove_orphaned_initialize
after_destroy :remove_orphaned
private
def remove_orphaned_initialize
@instvariable = self.movies
end
def remove_orphaned
@instvariable.each do |m|
m.destroy if m.actors.empty? and m.titles.empty? ##movies also have habtm with Title
end
end
end
如果我删除一个演员记录,那么孤儿电影不会被删除,因为 remove_orphaned 中的@instvariable 是 nil
你能解释一下我是如何实现它的吗?
如果我在 destroy 之前尝试 cal remove_orphaned ,那么 m.actors 将永远不会为空.. 因为当前的医生实例尚未删除