Peter Tretiakov
Peter Tretiakov

Reputation: 3410

Run update methods of model from another model

I have Transaction and Debt models.

transaction has_one: :debt
debt belongs_to: :transaction

When user create transaction and mark it as debt, Transaction model creates transaction.debt and in Debt model I have all logic for working with debts: run before_create and after_create methods.

So, I need the same behavior for updating transaction. Can I just run update methods (before_update and after_update) of Debt model from Transaction model without any update attributes?

As I understand all update methods, like update and update_attributes require some attributes for updating.

Thanks for any help!

Upvotes: 0

Views: 545

Answers (2)

Skelz0r
Skelz0r

Reputation: 114

You can run specific callback, thanks to ActiveRecord context, like this :

transaction.run_callbacks(:update)

Upvotes: 1

Shadwell
Shadwell

Reputation: 34784

If you define the before_update and after_update callbacks as actual methods then you can call them directly outside of the callbacks.

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

Those callbacks will be called by active record when the debt is updated in the usual way but are also available to you to call from your transaction:

self.debt.do_before
self.debt.do_after

Upvotes: 0

Related Questions