views:

280

answers:

2

I have a table where I am dumping some transaction data.

I have a transaction model. In it, there is a before_save in which I process the transaction through the credit_card gateway and use the results to fill out the rest of the fields in the transaction model.

I have a Transaction Observer watching that sends out a notification when It sees a new transaction. It then attempts to save the results of that attempt IN THE TRANSACTION using update_attribute.

This is unsurprisingly causing an infinite loop since the observer is triggering the before_save and around we go.

Is there a way to update one or two attributes in the transaction record without triggering the before_save callback? Is my only solution to move the notification results to another table?

A: 

Quick and untested, but the basic approach I use is to allow a condition on the callback. Condition can be whatever you want obviously.

class ModelWithCallback < ActiveRecord::Base

  before_save :update_stuff, :if => :update_needed?

  private
    def update_stuff
      ## Your callback code
    end

    def update_needed?
      !(changed.any?{ |field| field == "name" || field == "address")
    end
end
railsninja
+1  A: 

There is a private ActiveRecord methods that you can use:

update_without_callbacks

since it is private, you need to use send

transaction.send(:update_without_callbacks)
ez
Amazing! I'm not sure its a good idea to use that to often, but it certainly works here. Thanks!
Mike Williamson
This is something that maybe used in a pinch on the console but I don't know whether it's great idea to have it in your code.
railsninja