2014-05-05 86 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'中有一些债务变化,他们将不会被保存。现在我明白了,我的问题并不清楚,但实际上我需要从交易模型中更新债务,但没有任何属性。 –

相关问题