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?
✗ Incorrect
The
before_add callback runs right before an object is added to an association.What argument does an association callback method receive?
✗ Incorrect
Association callbacks receive the object being added or removed as an argument.
If a
before_add callback raises an error, what happens?✗ Incorrect
Raising an error in
before_add stops the object from being added.Which association type supports
before_add callbacks?✗ Incorrect
before_add is commonly used with has_many associations.Where do you specify association callbacks in Rails?
✗ Incorrect
You specify callbacks like
before_add inside the association declaration in the model.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.