2016-10-12 91 views
0

after_commithas_many關係更新並且記錄被銷燬時,不會觸發回調。Rails has_many使用關聯ID不會調用回調銷燬

我有我的控制器的關係

class Expertise 
    has_many :doctor_expertises 
    has_many :doctor_profiles, through: :doctor_expertises 

class DoctorExpertise 
    belongs_to :doctor_profile 
    belongs_to :expertise 

    after_commit :do_something 

    def do_something 
    # not called when record destroyed 
    end 

我用下面的方法來更新has_many關係

def create 
    doc = DoctorProfile.find(params[:doctor_id]) 
    doc.expertise_ids = params[:expertise_ids].select do |x| 
     x.to_i > 0 
    end 
    doc.save! 

    render json: doc.expertises 
    end 

我知道我應該在的關係可以用updatedestroy。但是,爲什麼after_commit在銷燬時不會被記錄調用?

我猜這跟我設置doc.expertise_ids的方式沒有觸發回調。但是,我無法找到有關此方法的任何文檔,只是簡要地爲here。是否有文件證實或否認這種懷疑或有其他事情發生?

回答

1

從你鏈接的RailsGuides:

加盟模式的自動刪除是直接的,沒有破壞回調被觸發。

雖然沒有說明有關after_commit它很可能沒有被解僱過

我認爲你正在尋找的答案就在這裏:

Howto use callbacks in a has_many through association?

您需要在has_many聲明中用戶after_remove