0
0
Ruby on Railsframework~10 mins

Dependent destroy and nullify 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 make associated comments deleted when a post is deleted.

Ruby on Rails
class Post < ApplicationRecord
  has_many :comments, [1]
end
Drag options to blanks, or click blank then click option'
Adependent: :destroy
B:dependent => :destroy
Cdependent: :nullify
D:dependent => :nullify
Attempts:
3 left
💡 Hint
Common Mistakes
Using hash rocket syntax (:dependent => :destroy) instead of the newer symbol syntax.
Using :nullify instead of :destroy when you want to delete associated records.
2fill in blank
medium

Complete the code to nullify the user_id in posts when a user is deleted.

Ruby on Rails
class User < ApplicationRecord
  has_many :posts, [1]
end
Drag options to blanks, or click blank then click option'
Adependent: :destroy
Bdependent: :nullify
Cdependent: :restrict_with_error
Ddependent: :delete_all
Attempts:
3 left
💡 Hint
Common Mistakes
Using :destroy deletes the posts instead of nullifying the user_id.
Using :delete_all deletes posts without callbacks.
3fill in blank
hard

Fix the error in the association to properly destroy comments when a post is deleted.

Ruby on Rails
class Post < ApplicationRecord
  has_many :comments, dependent: [1]
end
Drag options to blanks, or click blank then click option'
A:nullify
B:restrict_with_exception
C:destroy
D:delete_all
Attempts:
3 left
💡 Hint
Common Mistakes
Using :delete_all skips callbacks and may cause issues.
Using :nullify does not delete comments.
4fill in blank
hard

Fill both blanks to nullify the foreign key and prevent deletion if posts exist.

Ruby on Rails
class User < ApplicationRecord
  has_many :posts, [1], [2]
end
Drag options to blanks, or click blank then click option'
Adependent: :nullify
Bdependent: :restrict_with_error
Cdependent: :destroy
Ddependent: :delete_all
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use multiple dependent options in one association.
Confusing :destroy with :nullify.
5fill in blank
hard

Fill all three blanks to create a hash of post titles and their comment counts, only for posts with comments.

Ruby on Rails
post_comment_counts = posts.each_with_object({}) { |[3], h| h[[1]] = [2] if [3].comments.any? }
Drag options to blanks, or click blank then click option'
Apost.title
Bpost.comments.count
Cpost
Dposts
Attempts:
3 left
💡 Hint
Common Mistakes
Using the collection name instead of the loop variable.
Using the wrong attribute for keys or values.