In Rails, if a before_save callback returns false, what is the effect on the save operation?
class User < ApplicationRecord before_save :check_status def check_status return false if inactive? end end user = User.new(status: 'inactive') user.save
Think about how returning false in a before_save callback affects the transaction.
In Rails, returning false from a before_save callback halts the callback chain and prevents the save operation from completing.
Choose the correct way to define an after_commit callback in a Rails model.
Consider the options for specifying when the callback runs.
The after_commit callback can specify the timing with on: :create, on: :update, or on: :destroy. Option D correctly uses this syntax.
Given the following model, why does the record still get deleted despite the before_destroy callback?
class Post < ApplicationRecord before_destroy :check_if_published def check_if_published throw(:abort) if published? end end post = Post.find(1) post.destroy
Check the condition inside the callback method.
If published? returns false, the throw(:abort) is never called, so the deletion proceeds.
status after save with after_save callback?Consider this model with an after_save callback that changes an attribute. What is the value of status after save completes?
class Task < ApplicationRecord after_save :mark_completed def mark_completed update_column(:status, 'completed') end end task = Task.create(status: 'pending') task.reload status_value = task.status
Think about when after_save runs and what update_column does.
The after_save callback runs after the initial save. The update_column updates the attribute directly in the database without callbacks, so after reload, status is "completed".
In Rails, which callback guarantees that the code inside it runs only after the database transaction has been successfully committed?
Think about the difference between saving and committing a transaction.
after_commit runs only after the database transaction is fully committed, ensuring data is saved permanently.