Bird
Raised Fist0
Ruby on Railsframework~20 mins

Nested attributes in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Nested Attributes Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when saving nested attributes with reject_if condition?

Consider a Rails model Order that accepts_nested_attributes_for :items with reject_if: :all_blank. What will be the result when saving an order with one item having all blank fields?

Ruby on Rails
class Order < ApplicationRecord
  has_many :items
  accepts_nested_attributes_for :items, reject_if: :all_blank
end

order = Order.new(items_attributes: [{name: '', quantity: ''}])
order.save
items_count = order.items.count
AThe order saves and items_count is nil because items are not loaded
BThe order saves and one blank item is created, so items_count is 1
CThe order fails to save due to validation errors on items
DThe order saves but no items are created, so items_count is 0
Attempts:
2 left
💡 Hint

Think about what reject_if: :all_blank does when nested attributes are blank.

📝 Syntax
intermediate
2:00remaining
Which nested attributes syntax correctly updates a child record?

Given a Post model with many comments and accepts_nested_attributes_for :comments, which params hash correctly updates the comment with id 5?

Ruby on Rails
params = {
  post: {
    comments_attributes: {
      '5' => { content: 'Updated comment' }
    }
  }
}
A{ post: { comments_attributes: { '5' => { content: 'Updated comment' } } } }
B{ post: { comments_attributes: [{ content: 'Updated comment' }] } }
C{ post: { comments_attributes: { id: 5, content: 'Updated comment' } } }
D{ post: { comments_attributes: [{ id: 5, content: 'Updated comment' }] } }
Attempts:
2 left
💡 Hint

Remember that nested attributes for updating use a hash with keys as string ids.

🔧 Debug
advanced
2:00remaining
Why does this nested attribute update fail silently?

Given the following code, why does updating the nested profile of a User not change the profile's name?

Ruby on Rails
class User < ApplicationRecord
  has_one :profile
  accepts_nested_attributes_for :profile
end

user = User.find(1)
user.update(profile_attributes: { id: user.profile.id, name: 'New Name' })
user.profile.name
AThe profile's name is not updated because the <code>profile</code> association is not marked as <code>autosave: true</code>
BThe profile's name is not updated because <code>profile_attributes</code> is missing <code>allow_destroy: true</code>
CThe profile's name is not updated because the <code>id</code> key is missing in the nested attributes
DThe profile's name is not updated because the <code>profile</code> model has validations that fail silently
Attempts:
2 left
💡 Hint

Think about what Rails needs to save changes to associated records.

❓ state_output
advanced
2:00remaining
What is the state of child records after nested attributes update with _destroy flag?

Given a Project with many tasks and accepts_nested_attributes_for :tasks, allow_destroy: true, what happens after this update?

Ruby on Rails
project = Project.find(1)
project.update(tasks_attributes: [{ id: 10, _destroy: '1' }])
remaining_tasks = project.tasks.pluck(:id)
AThe update fails because _destroy must be a boolean true, so remaining_tasks includes 10
BThe task with id 10 is deleted, so remaining_tasks does not include 10
CThe task with id 10 is marked as completed but not deleted, so remaining_tasks includes 10
DThe task with id 10 is archived but still present, so remaining_tasks includes 10
Attempts:
2 left
💡 Hint

Recall what the _destroy flag does in nested attributes.

🧠 Conceptual
expert
3:00remaining
Why use nested attributes instead of manual child record management?

Which is the best explanation for why Rails provides accepts_nested_attributes_for to handle nested attributes?

AIt enforces database-level foreign key constraints to prevent orphaned child records
BIt automatically validates all child records without needing explicit validation rules in child models
CIt simplifies form handling by allowing parent and child records to be created or updated in one step, reducing manual code and errors
DIt replaces the need for any callbacks or custom logic in models managing associations
Attempts:
2 left
💡 Hint

Think about the developer experience when working with forms that include related data.

Practice

(1/5)
1. What does accepts_nested_attributes_for do in a Rails model?
easy
A. Validates the presence of nested attributes in the parent model.
B. Creates a new database table for nested models automatically.
C. Allows a parent model to accept and save attributes for its associated child models.
D. Generates controller actions for nested resources.

Solution

  1. Step 1: Understand the purpose of accepts_nested_attributes_for

    This method is used in a parent model to allow it to accept attributes for its associated child models.
  2. Step 2: Recognize what it enables in Rails

    It enables saving or updating child model data through the parent model's form or controller.
  3. Final Answer:

    Allows a parent model to accept and save attributes for its associated child models. -> Option C
  4. Quick Check:

    accepts_nested_attributes_for = Accept nested child attributes [OK]
Hint: Think: parent model saving child data together [OK]
Common Mistakes:
  • Confusing it with database table creation
  • Assuming it validates nested attributes automatically
  • Thinking it generates controller code
2. Which of the following is the correct syntax to enable nested attributes for a child model named tasks inside a parent model?
easy
A. accepts_nested_attributes_for :tasks
B. accepts_nested_attributes_for :task
C. accepts_nested_attributes_for tasks
D. accepts_nested_attributes_for 'tasks'

Solution

  1. Step 1: Identify the correct argument type

    The method expects a symbol representing the association name, which is plural if the association is has_many.
  2. Step 2: Match the association name

    Since the child model is tasks (plural), the correct syntax is accepts_nested_attributes_for :tasks.
  3. Final Answer:

    accepts_nested_attributes_for :tasks -> Option A
  4. Quick Check:

    Use symbol with plural association name [OK]
Hint: Use symbol and plural for has_many associations [OK]
Common Mistakes:
  • Using singular instead of plural for has_many
  • Passing string instead of symbol
  • Omitting colon before association name
3. Given the following models and controller snippet, what will happen when creating a Project with nested tasks_attributes?
class Project < ApplicationRecord
  has_many :tasks
  accepts_nested_attributes_for :tasks
end

class Task < ApplicationRecord
  belongs_to :project
end

# In ProjectsController
params = { project: { name: 'Build App', tasks_attributes: [{ title: 'Design UI' }, { title: 'Write Tests' }] } }
@project = Project.new(params[:project])
@project.save
medium
A. A new project and two associated tasks will be saved in the database.
B. Only the project will be saved; tasks will be ignored.
C. An error will occur because nested attributes are not permitted in the controller.
D. The project will save but tasks will be saved without association.

Solution

  1. Step 1: Check model setup for nested attributes

    The Project model uses accepts_nested_attributes_for :tasks, allowing nested task attributes.
  2. Step 2: Analyze controller params and save

    The params include tasks_attributes with two tasks. Calling Project.new with these params and then save will save the project and its tasks together.
  3. Final Answer:

    A new project and two associated tasks will be saved in the database. -> Option A
  4. Quick Check:

    Nested attributes save parent and children together [OK]
Hint: Nested attributes save parent and children in one go [OK]
Common Mistakes:
  • Assuming tasks are ignored without explicit permit
  • Thinking save fails without controller strong params shown
  • Believing tasks save without association
4. Identify the error in the following controller code when trying to save nested attributes:
def project_params
  params.require(:project).permit(:name, tasks_attributes: [:title])
end

@project = Project.new(project_params)
@project.save
Assuming the models are set up correctly with accepts_nested_attributes_for :tasks.
medium
A. The require method should be permit instead.
B. The accepts_nested_attributes_for should be in the controller, not the model.
C. The tasks_attributes key should be a string, not a symbol.
D. The permit method is missing the :id key inside tasks_attributes.

Solution

  1. Step 1: Understand strong parameters for nested attributes

    When updating nested records, Rails expects the :id key to identify existing child records.
  2. Step 2: Check the permit call

    The permit call only allows :title inside tasks_attributes, missing :id. This causes update failures or errors.
  3. Final Answer:

    The permit method is missing the :id key inside tasks_attributes. -> Option D
  4. Quick Check:

    Permit :id for nested updates [OK]
Hint: Permit :id inside nested attributes for updates [OK]
Common Mistakes:
  • Omitting :id in nested strong params
  • Confusing require and permit methods
  • Placing accepts_nested_attributes_for in controller
5. You have a Survey model with many questions. You want to allow users to add, update, and remove questions through the survey form. Which combination of code is needed to correctly handle nested attributes and allow question removal?
hard
A. In Survey model: accepts_nested_attributes_for :questions, reject_if: :all_blank In controller: permit questions_attributes with :content, :_destroy
B. In Survey model: accepts_nested_attributes_for :questions, allow_destroy: true In controller: permit questions_attributes with :id, :content, :_destroy
C. In Survey model: has_many :questions In controller: permit questions_attributes with :id, :content
D. In Survey model: accepts_nested_attributes_for :questions In controller: permit questions_attributes with :content only

Solution

  1. Step 1: Enable nested attributes with destroy option

    To allow removal of nested records, accepts_nested_attributes_for must include allow_destroy: true.
  2. Step 2: Permit necessary keys in controller

    The controller must permit :id to identify records, :content for data, and :_destroy to mark records for deletion.
  3. Final Answer:

    In Survey model: accepts_nested_attributes_for :questions, allow_destroy: true In controller: permit questions_attributes with :id, :content, :_destroy -> Option B
  4. Quick Check:

    allow_destroy and permit :_destroy for removals [OK]
Hint: Use allow_destroy and permit :_destroy to remove nested records [OK]
Common Mistakes:
  • Forgetting allow_destroy in model
  • Not permitting :_destroy in strong params
  • Permitting only :content without :id
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard