I have a Rails object with after_update
callback that sends a record to a queue. And the problem is that I noticed sometimes the queue is being processed faster than the object is actually being updated.
My question: is after_update
called not after the object updating ended, but when it started? What callback I need if I want to do something with it only after update is successful?
after_save , after_create , after_update are called within the transaction block, so they will be executed before executing the SQL statement. If you want to do something when the statement execution is completed, you should use after_commit callback.
Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
Does Update_all trigger callbacks in rails? permalink #update_all(updates) ⇒ Object It does not instantiate the involved models and it does not trigger Active Record callbacks or validations.
Rails provides before and after actions in controllers as an easy way to call methods before or after executing controller actions as response to route requests. Action Callbacks can be particularly helpful when implementing authentication/authorization for example, and are heavily used by gems such as Devise.
after_save
, after_create
, after_update
are called within the transaction block, so they will be executed before executing the SQL statement.
If you want to do something when the statement execution is completed, you should use after_commit callback.
If you consult the Rails documentation you will find a lot of callbacks you can use. The best for this job might be "after_commit":
This is straight from the Rails Docs (link at the bottom)
3.1 Creating an Object
before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
after_commit/after_rollback
3.2 Updating an Object
before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save
after_commit/after_rollback
3.3 Destroying an Object
before_destroy
around_destroy
after_destroy
Rails DOcs: http://guides.rubyonrails.org/active_record_callbacks.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With