Complete the code to make associated comments deleted when a post is deleted.
class Post < ApplicationRecord has_many :comments, [1] end
In Rails, to delete associated records when the parent is deleted, use dependent: :destroy in the association.
Complete the code to nullify the user_id in posts when a user is deleted.
class User < ApplicationRecord has_many :posts, [1] end
Using dependent: :nullify sets the foreign key to NULL instead of deleting the associated records.
Fix the error in the association to properly destroy comments when a post is deleted.
class Post < ApplicationRecord has_many :comments, dependent: [1] end
The :destroy option ensures callbacks run and associated comments are deleted.
Fill both blanks to nullify the foreign key and prevent deletion if posts exist.
class User < ApplicationRecord has_many :posts, [1], [2] end
Using dependent: :nullify sets foreign keys to null, and dependent: :restrict_with_error prevents deletion if posts exist. However, only one dependent option is allowed, so this is a trick question to understand options.
Fill all three blanks to create a hash of post titles and their comment counts, only for posts with comments.
post_comment_counts = posts.each_with_object({}) { |[3], h| h[[1]] = [2] if [3].comments.any? }This uses each_with_object to build a hash where keys are post titles and values are the count of comments, only for posts with comments.