【发布时间】:2015-08-18 05:29:36
【问题描述】:
我有两个 AR 模型和第三个 has_many :through 加入模型,如下所示:
class User < ActiveRecord::Base
has_many :ratings
has_many :movies, through: :ratings
end
class Movie < ActiveRecord::Base
has_many :ratings
has_many :users, through: :ratings
end
class Rating < ActiveRecord::Base
belongs_to :user
belongs_to :movie
after_destroy do
puts 'destroyed'
end
end
有时,用户会想要直接删除电影(不直接破坏评级)。但是,当我这样做时:
# puts user.movie_ids
# => [1,2,3]
user.movie_ids = [1, 2]
评级的after_destroy 回调未被调用,尽管加入记录已被适当地删除。如果我像这样修改我的用户模型:
class User < ActiveRecord::Base
has_many :ratings
has_many :movies,
through: :ratings,
before_remove: proc { |u, m| Rating.where(movie: m, user: u).destroy_all }
end
一切正常,但这真的很难看,Rails 然后再次尝试删除连接模型。
我怎样才能使用dependent: :destroy 策略而不是dependent: :delete?
【问题讨论】:
-
from doco 如果与
:through选项一起使用,连接模型上的关联必须是belongs_to,并且被删除的记录是连接记录,而不是比关联的记录。
标签: ruby-on-rails ruby-on-rails-4 rails-activerecord