2014-05-05 81 views
0

我有TransactionDebt模型。從另一個模型運行更新模型的方法

transaction has_one: :debt 
debt belongs_to: :transaction 

當用戶創建事務並將其標記爲債務,Transaction模型創建transaction.debtDebt模型我都邏輯與債務工作:運行before_createafter_create方法。

所以,我需要相同的行爲來更新事務。我可以運行更新方法(before_updateafter_updateDebt模型從Transaction模型沒有任何更新屬性?

據我所知,所有更新方法,如updateupdate_attributes需要一些更新的屬性。

感謝您的幫助!

回答

0

如果您將before_updateafter_update回調定義爲實際方法,那麼您可以直接在回調之外調用它們。

class Debt < ActiveRecord::Base 

    before_update :do_before 
    after_update :do_after 

    def do_before 
    # Before update processing 
    end 

    def do_after 
    # After update processing 
    end 

這些回調將通過活動記錄時調用債務以通常的方式被更新,但也可爲您從您的交易撥打:

self.debt.do_before 
self.debt.do_after 
1

可以運行特定的回調,謝謝到ActiveRecord上下文,如下所示:

transaction.run_callbacks(:update) 
+0

Thanks!在我的情況下,它會是'self.debt.run_callbacks(:update)',但是有一個問題:實際上在不更新債務,它只運行它的更新方法。我的意思是,如果我在'before_update'中有一些債務變化,他們將不會被保存。現在我明白了,我的問題並不清楚,但實際上我需要從交易模型中更新債務,但沒有任何屬性。 –

相關問題