Ruby on rails 4 协会不';无法使用依赖项删除:true
我有一个用于Ruby on rails 4 协会不';无法使用依赖项删除:true,ruby-on-rails-4,associations,destroy,Ruby On Rails 4,Associations,Destroy,我有一个用于项目和照片模型的加入模型 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
项目
和照片
模型的加入模型
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
class ItemPhoto
当删除一张照片时,如果它是最后一张照片(某种参考计数),我想删除该项目,或者至少能够在之前运行一些代码
这可能吗?实现这一点的一种方法是使用关联回调,如删除后的
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
class-Photo
此处的文档:(无直接链接,但搜索关联回调)