0

我通过关联使用 has_many 并且无法让 before_destroy 回调触发。我正在使用 Relating 类来关联模型。

class Relating < ActiveRecord::Base
  belongs_to :relater, :polymorphic => true
  belongs_to :related, :polymorphic => true

  before_destroy :unset_reminders
end

例如,用户可以将 TvShows 添加到收藏夹列表 User.rb:

has_many :tv_shows, :through => :relateds, :source => :related, :source_type => 'TvShow'

我遇到的问题与删除此关联记录有关。

我可以通过以下方式关联用户和电视节目:

user = User.find(1)
show = TvShow.find(1)
user.tv_shows << show

但是当我想删除这个关联时, before_destroy 不是由以下触发的:

user.tv_shows.delete(show)

但是,如果我手动销毁相关记录,它会触发回调:

r = Relating.find(8012)
r.destroy

我怎样才能为此触发之前的销毁?

谢谢

4

1 回答 1

1

delete方法不会触发此处文档中提到的回调。试试destroy吧。

Update: I didn't realize you were trying to destroy the join record and not the show itself. I'm surprised delete works at all but perhaps that is a feature of has_many :through. How about:

user.relateds.where(tv_show_id: show.id).destroy
于 2012-06-26T22:58:24.647 回答