0
0
Ruby on Railsframework~10 mins

Association callbacks in Ruby on Rails - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a callback that runs after a comment is created.

Ruby on Rails
class Comment < ApplicationRecord
  belongs_to :post
  after_[1] :notify_post_author

  def notify_post_author
    # notification logic here
  end
end
Drag options to blanks, or click blank then click option'
Asave
Bcreate
Cupdate
Ddestroy
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'after_save' which runs on both create and update, not just creation.
Using 'after_destroy' which runs after deletion, not creation.
2fill in blank
medium

Complete the code to run a callback before a post is destroyed to clean up associated comments.

Ruby on Rails
class Post < ApplicationRecord
  has_many :comments, dependent: :destroy
  before_[1] :cleanup_comments

  def cleanup_comments
    comments.destroy_all
  end
end
Drag options to blanks, or click blank then click option'
Asave
Bupdate
Ccreate
Ddestroy
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'before_save' which runs on create and update, not on destroy.
Using 'after_destroy' which runs after deletion, too late for cleanup.
3fill in blank
hard

Fix the error in the callback method name to correctly run after a post's comments are added.

Ruby on Rails
class Post < ApplicationRecord
  has_many :comments, after_add: :[1]

  def log_comment_addition(comment)
    # log logic here
  end
end
Drag options to blanks, or click blank then click option'
Alog_comment_addition
Blog_comment_added
Clog_comment_add
Dlog_added_comment
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name that does not match the callback symbol.
Misnaming the callback method causing it not to run.
4fill in blank
hard

Fill both blanks to define a callback that runs before adding a tag to a post and calls the correct method.

Ruby on Rails
class Post < ApplicationRecord
  has_many :tags, [1]: :[2]

  def check_tag_limit(tag)
    # limit check logic
  end
end
Drag options to blanks, or click blank then click option'
Abefore_add
Bafter_add
Ccheck_tag_limit
Dvalidate_tag_limit
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'after_add' instead of 'before_add' for pre-add checks.
Mismatching method names causing callbacks not to trigger.
5fill in blank
hard

Fill all three blanks to define callbacks that run before adding and after removing categories from a product.

Ruby on Rails
class Product < ApplicationRecord
  has_many :categories, [1]: :[2], [3]: :log_category_removal

  def log_category_addition(category)
    # log addition
  end
end
Drag options to blanks, or click blank then click option'
Abefore_add
Blog_category_addition
Cafter_remove
Dbefore_remove
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'before_remove' instead of 'after_remove' for post-removal actions.
Mismatching method names causing callbacks not to execute.