Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding after_update callback in Rails 4

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?

like image 700
Nadiya Avatar asked Apr 09 '17 19:04

Nadiya


People also ask

Which of the given callbacks is executed after the After_update?

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.

What are the relational callbacks in rails?

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?

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.

What is controller callback in rails?

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.


2 Answers

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.

like image 52
pan.goth Avatar answered Sep 24 '22 02:09

pan.goth


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

like image 32
Alexander Luna Avatar answered Sep 23 '22 02:09

Alexander Luna