【发布时间】:2016-11-18 15:58:46
【问题描述】:
我有这些模型
class User < ActiveRecord::Base
has_many :user_functions, :dependent => :destroy
has_many :functions, :through => :user_functions
accepts_nested_attributes_for :functions, allow_destroy: true
链接表的型号:
class UserFunction < ActiveRecord::Base
belongs_to :user, inverse_of: :user_functions
belongs_to :function, inverse_of: :user_functions
after_destroy :unplan_items
after_create :plan_items
当然还有功能模型,但这就像用户......
现在,当我在测试中执行以下操作时:
@user.functions = [@functions]
@user.save
expect(@user.planned_items.count).to eq(1)
@user.functions = []
@user.save
我注意到回调 after_destroy 没有被调用。为什么会这样,我该如何避免这种情况。每次销毁 UserFunction 时都需要执行某些步骤...
我相信这与:https://github.com/rails/rails/issues/7618(虽然我使用的是 rails 4.2.5)有关。 after_create 运行良好...
【问题讨论】:
-
设置一个实例变量为[]然后保存与调用destroy是不一样的。
-
对不起,我没有关注你。 @user 指的是某个用户,该用户具有通过 user_functions 表链接到他的 3 个函数。将函数设置为 [] 会有效地删除这些记录 (user_functions)。为什么这不经历那些毁灭?
标签: ruby-on-rails rails-activerecord