Performance: Callbacks overview
Callbacks affect the server response time and database transaction speed by adding extra processing steps during model lifecycle events.
class User < ApplicationRecord after_commit :enqueue_heavy_job def enqueue_heavy_job HeavyJob.perform_later(self.id) end end
class User < ApplicationRecord before_save :heavy_computation def heavy_computation # complex calculations or external API calls end end
| Pattern | Server Processing | Database Impact | Response Delay | Verdict |
|---|---|---|---|---|
| Heavy logic in before_save | High CPU usage | Blocks transaction | Increases latency | [X] Bad |
| Lightweight after_commit with background job | Minimal CPU | Non-blocking | Fast response | [OK] Good |
before_save :method_name to run a method before saving a record.after_save runs after saving, on_save is invalid, and the block syntax is incorrect here.class User < ApplicationRecord
before_create :set_default_role
def set_default_role
self.role ||= 'guest'
end
endbefore_create callback runs the method set_default_role before the record is created in the database.self.role to 'guest' only if it is currently nil or falsey (using ||=).class Post < ApplicationRecord
before_save :check_title
def check_title
if title.blank?
errors.add(:title, "can't be blank")
throw :abort
end
end
endbefore_save callback runs check_title before saving.throw :abort is the correct way to stop saving if validation fails.log_update only after a record is updated but not created. Which callback should you use?after_save runs after both create and update, but after_update runs only after updates.log_update only after updates, after_update is the correct choice.Pass the test and this pattern moves unknown