From the Rails guide
Callbacks are methods that are called at specific moments during the life cycle of an object. Callbacks allow you to write code that is always executed when an Active Record object is created / saved / updated / deleted / verified / loaded from the database, etc.
Active Record callbacks fire events before and after when an Active Record object such as Model is updated or deleted and its state changes. Any processing can be performed in the event.
Example) Output a log when member data is deleted.
app/models/member.rb
class Member < ApplicationRecord
Abbreviation
after_destroy do
Rails.logger.info "Member is deleted: #{self.attributes}"
end
end
When a member is deleted, the process in ʻafter_destroy` is executed.
Below are some examples of callbacks available in Active Record. before_ can define the processing before the trigger, around_ can define the processing before and after the trigger, and after_ can define the processing after the trigger. If it is before_validation, it occurs before the validation process performed by create and update.
Callback point | create | update | destroy |
---|---|---|---|
before_validation | ○ | ○ | × |
after_validation | ○ | ○ | × |
before_save | ○ | ○ | × |
around_save | ○ | ○ | × |
after_save | ○ | ○ | × |
before_create | ○ | × | × |
around_create | ○ | × | × |
after_create | ○ | × | × |
before_update | ○ | ○ | × |
around_update | ○ | ○ | × |
after_update | ○ | ○ | × |
before_destroy | × | × | ○ |
around_destroy | × | × | ○ |
after_destroy | × | × | ○ |
During development, I sometimes wanted to check the behavior when the deletion process failed, so I was able to make it fail by doing the following.
app/models/member.rb
class Member < ApplicationRecord
Abbreviation
before_destroy { throw(:abort) }
end
Callback processing can be intentionally stopped by writing throw (: abort)
.
--Since the callback is set in the model, the logic cannot be seen from the controller, and the developer may execute unexpected processing. --If you use a lot of callbacks or perform complicated processing, it becomes a fat model.
--Rails Guide --Active Record Callbacks -Perfect Ruby on Rails [enhanced and revised edition]
Recommended Posts