user1265795
user1265795

Reputation: 11

ruby on rails after_update callback hooks issue

In my Rails Application, I have after_update callback. But this callback is executed when my record is first time created using save method and when it is updated using update_attributes.

So I want a way using which the callback/method must be called when it is coming to update method but currently it is getting executing when it is coming to create as well as update method.

I think update_attribute also call internally a save method, because of this issue is coming.

So is there any way using which I can call my hook when record is updated and not saved.

I found one way using attr_accessors but I wanted some other way as maintaining these flags will be very difficult for my app

Upvotes: 1

Views: 3568

Answers (2)

rajibchowdhury
rajibchowdhury

Reputation: 5544

How about this

after_update do |model| 
  model.name = model.name.capitalize unless model.new_record?
end

Upvotes: 1

Ben
Ben

Reputation: 13615

after_update only gets called after a update of the model. For it to get called when a model is created, you must update its attributes after .save is called on the model. .update_attribute and .update_attributes is not the create of a model, it is actually updating the model. .update_attribute calls the .save method internally. .save is called to save the state of the model, new or updated. When you call it, ActiveRecord writes the new state to the database. When a model is created or updated, it is always done trough the .save method

Upvotes: 1

Related Questions