views:

228

answers:

3

I have a model that uses after_update to log changes. There is a case where I would like to make a change to the model without activating this logging mechanism. Is there a way to pass in a parameter to after_update, or skip it all together?

I would like a nice solution to this, and am willing to remove after_update if there is a better way to go about it.

A: 

You could add a boolean to your model that is something like log_last_update and check that in the after_update callback.

twolfe18
+1  A: 

I would go with the approach of adding a boolean to the model as suggested but would then write a method to help set and clear the flag after your update. e.g.

def without_logging_changes_to(model)
  # store current value of the flag so it can be restored
  # when we leave the block
  remembered_value = model.log_update
  model.log_update = false
  begin
    yield
  ensure
    model.log_update = remembered_value
  end
end

Then to use it:

without_logging_changes_to my_model do
  my_model.update_attributes(updates)
end
mikej
this is what I have done, but it feels hackish. I guess for now there's no way around it using rails
Ori Cohen
If you do come up with a more elegant solution please let me know. Thanks.
mikej
A: 
class MyModel < ActiveRecord::Base

  after_update :do_something

  attr_accessor :should_do_something



  def should_do_something?
    should_do_something != false
  end

  def do_something
    if should_do_something?
      ...
    end
  end

end


y = MyModel.new
y.save! # callback is triggered

n = MyModel.new
n.should_do_something = false
n.save! # callback isn't triggered
Simone Carletti