Christian Fazzini
Christian Fazzini

Reputation: 19713

Create callback executing foobar twice

My model looks like this:

  after_create :foobar
  after_update :foobar

  def foobar
    update_attributes(:foo => 'bar')
  end

Whenever I create an object. It calls foobar (after_create callback). But it also automatically triggers the after_update callback.

Basically, when I create an object its calling foobar twice.

How can I prevent this?

Upvotes: 1

Views: 173

Answers (1)

jefflunt
jefflunt

Reputation: 33954

In after_create you're calling update_attributes() which triggers the after_update callback.

Basically you're calling it twice. You need to figure out what the proper flow is for your program, and make it such that foobar only gets called once. Right now, the code you've written is executing as designed.

One suggestion would be using before_[action] attributes instead to modify the fields in the incoming object. That way the object only gets saved once. The way you've written it, new objects get saved twice - once when they're created, and once when they're updated via update_attributes.

I see that this is example code, but I'm not sure how, in after_update, since you explicitly make ANOTHER update, how this isn't getting wrapped up in an infinite loop. Might be able to give a better answer if you post actual code.

Upvotes: 2

Related Questions