我有item_photos
和item
个模型的加入模型photo
class ItemPhoto < ActiveRecord::Base
belongs_to :item
belongs_to :photo
end
class Item < ActiveRecord::Base
has_many :item_photos
has_many :photos, through: :item_photos, dependent: :destroy
end
class Photo < ActiveRecord::Base
has_many :item_photos, dependent: :destroy
has_many :items, through: :item_photos, dependent: :destroy
end
删除照片时,我想删除最后一个项目(引用计数),或者至少能够在之前运行一些代码
这可能吗?
答案 0 :(得分:0)
执行此操作的一种方法是使用关联回调,例如after_remove
。
class Photo < ActiveRecord::Base
has_many :item_photos, dependent: :destroy
has_many :items, through: :item_photos, dependent: :destroy, after_remove: :do_stuff
private
def do_stuff
# ...
end
end
此处的文档:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html(没有直接链接,但搜索关联回调)