0
0
Ruby on Railsframework~5 mins

Association callbacks in Ruby on Rails - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What are association callbacks in Rails?
Association callbacks are special methods that run automatically when you add or remove objects from an association, like has_many or has_one. They help you run code during these changes.
Click to reveal answer
beginner
Name two common association callbacks in Rails.
Two common association callbacks are before_add and after_remove. They run before adding an object to an association and after removing an object, respectively.
Click to reveal answer
intermediate
How do you define a before_add callback on a has_many association?
You add it inside the association like this:<br>has_many :comments, before_add: :check_comment<br>Then define the method check_comment in your model to run before adding a comment.
Click to reveal answer
intermediate
What happens if a before_add callback throws an exception?
If a before_add callback raises an error, the object will NOT be added to the association. This lets you stop unwanted changes safely.
Click to reveal answer
intermediate
Can association callbacks access the object being added or removed? How?
Yes, association callbacks receive the object being added or removed as an argument. For example:<br>before_add :method_name where method_name(added_object) can use that object inside.
Click to reveal answer
Which callback runs before adding an object to a Rails association?
Abefore_add
Bafter_add
Cbefore_save
Dafter_remove
What argument does an association callback method receive?
ANo arguments
BThe parent model
CThe object being added or removed
DThe database connection
If a before_add callback raises an error, what happens?
AThe object is not added
BThe object is still added
CThe callback is ignored
DThe entire transaction rolls back
Which association type supports before_add callbacks?
AAll of the above
Bhas_many
Chas_one
Dbelongs_to
Where do you specify association callbacks in Rails?
AIn the routes file
BIn the controller
CIn the database schema
DInside the association declaration
Explain what association callbacks are and give an example of when you might use one.
Think about how Rails lets you run code when you add or remove related objects.
You got /3 concepts.
    Describe how to add a before_add callback to a has_many association and what happens if the callback raises an error.
    Focus on the association declaration and callback behavior.
    You got /3 concepts.