Learn about callbacks
- Callback is a method in Activerecord, used when the object needs it.
- Callback is often used to call and execute certain methods before and after the object has changes such as create, update, destroy, load data, validate, save, …
- Since callbacks are methods that should be declared in the model before use, we will have two ways to declare callbacks:
- Normal declaration
- Declare type block
1 2 | lưu ý : đối với cách khai báo này thì nó sử dụng cho toàn action controller, để áp dụng với một hoặc một số action cụ thể, ta viết |
- List of callbacks available in rails
Creating an Object
1 2 3 4 5 6 7 8 9 10 | before_validation after_validation before_save around_save before_create around_create after_create after_save after_commit/after_rollback |
Updating an Object
1 2 3 4 5 6 7 8 9 10 | before_validation after_validation before_save around_save before_update around_update after_update after_save after_commit/after_rollback |
Destroying an Object
1 2 3 4 5 | before_destroy around_destroy after_destroy after_commit/after_rollback |
To bypass the callback we can use the following
- Use the skip_callback method
- By the way, I talked more about the methods that can use callbacks in rails:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | create create! destroy destroy! destroy_all save save! save(validate: false) toggle! touch update_attribute update update! valid? |
Also the methods that ignore callbacks are:
1 2 3 4 5 6 7 8 9 10 11 | decrement! decrement_counter delete delete_all increment! increment_counter update_column update_columns update_all update_counters |
General In my opinion callbacks are an indispensable method when working with rails or any other language, through this article I hope to help you a little more in the process of learning callbacks, thank you for reading .
1 2 | Happy Coding |