0
0
Ruby on Railsframework~10 mins

Nested attributes 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 allow nested attributes for comments in the Post model.

Ruby on Rails
class Post < ApplicationRecord
  has_many :comments
  accepts_nested_attributes_for :[1]
end
Drag options to blanks, or click blank then click option'
Aposts
Bcomments
Cusers
Dauthors
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong association name in accepts_nested_attributes_for.
Forgetting to add accepts_nested_attributes_for altogether.
2fill in blank
medium

Complete the form helper to build fields for nested comments inside the post form.

Ruby on Rails
<%= form_with model: @post do |f| %>
  <%= f.text_field :title %>
  <%= f.fields_for :[1] do |c| %>
    <%= c.text_area :content %>
  <% end %>
<% end %>
Drag options to blanks, or click blank then click option'
Acomments
Bauthors
Cposts
Dusers
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong symbol in fields_for causing no nested fields to appear.
Not matching the association name exactly.
3fill in blank
hard

Fix the error in the controller to permit nested comment attributes.

Ruby on Rails
def post_params
  params.require(:post).permit(:title, comments_attributes: [:id, :content, :[1]])
end
Drag options to blanks, or click blank then click option'
Aauthor_id
Buser_id
C_destroy
Dpost_id
Attempts:
3 left
💡 Hint
Common Mistakes
Not permitting :_destroy causes nested record deletion to fail.
Permitting unrelated keys that do not affect nested attributes.
4fill in blank
hard

Fill both blanks to build a nested attributes hash for a new comment with content and mark it for destruction.

Ruby on Rails
post_attributes = {
  title: 'New Post',
  comments_attributes: {
    '0' => { content: [1], [2]: true }
  }
}
Drag options to blanks, or click blank then click option'
A'Great post!'
Bcontent
C_destroy
Ddestroy
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong key name instead of :_destroy.
Putting a non-string value for content.
5fill in blank
hard

Fill all three blanks to create a nested attributes hash for updating a comment's content and allowing its destruction.

Ruby on Rails
post_params = {
  post: {
    title: 'Updated Post',
    comments_attributes: {
      '0' => { id: [1], content: [2], [3]: true }
    }
  }
}
Drag options to blanks, or click blank then click option'
A42
B'Updated comment content'
C_destroy
Dcontent
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string instead of a number for id.
Forgetting to include :_destroy to allow deletion.