2016-11-18 15 views
1

我有這些模型鏈接表的after_destroy不會調用鏈接表

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工作正常,但...

+0

將實例變量設置爲[]然後保存它與調用destroy不同。 –

+0

抱歉,我沒有關注你。 @user指的是具有3個通過user_functions錶鏈接到他的函數的特定用戶。將函數設置爲[]可以有效刪除這些記錄(user_functions)。爲什麼不通過這些破壞? – rept

回答

2

當前rails使用:delete_all作爲has_many_through的默認策略。當我們在關聯上明確指定dependent: :destroy時,它僅調用:destroy_all

的文檔提到的建議,如果你需要回調使用的has_many :through: 在這裏看到的建議:http://guides.rubyonrails.org/association_basics.html

你應該使用的has_many:通過如果你需要驗證,回調, 或額外的屬性加入模型。

所以目前在做回調的after_createafter_destroy之間存在不一致。

這張貼在GitHub上這兩個問題中提到:

https://github.com/rails/rails/issues/7618

https://github.com/rails/rails/issues/27099

的修復,現在是明確提出:dependent => :destroy:through一部分。這將確保使用回調。

class User < ActiveRecord::Base 
    has_many :user_functions 
    has_many :functions, :through => :user_functions, :dependent => :destroy 
    accepts_nested_attributes_for :functions, allow_destroy: true