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?
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
Think about what reject_if: :all_blank does when nested attributes are blank.
The reject_if: :all_blank option prevents creation of nested records if all their attributes are blank. So the blank item is ignored, and no item is created. The order saves successfully with zero items.
Given a Post model with many comments and accepts_nested_attributes_for :comments, which params hash correctly updates the comment with id 5?
params = {
post: {
comments_attributes: {
'5' => { content: 'Updated comment' }
}
}
}Remember that nested attributes for updating use a hash with keys as string ids.
When updating nested records, Rails expects a hash where keys are string ids of the child records. Option A matches this format. Option A uses an array which is for creating new records. Option A is missing the key structure. Option A lacks the id to identify which comment to update.
Given the following code, why does updating the nested profile of a User not change the profile's name?
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
Think about what Rails needs to save changes to associated records.
By default, has_one associations do not autosave changes to the associated record unless autosave: true is set. Without it, nested attribute updates to profile won't persist changes. The id key is present, and validations are not mentioned as failing.
Given a Project with many tasks and accepts_nested_attributes_for :tasks, allow_destroy: true, what happens after this update?
project = Project.find(1) project.update(tasks_attributes: [{ id: 10, _destroy: '1' }]) remaining_tasks = project.tasks.pluck(:id)
Recall what the _destroy flag does in nested attributes.
When allow_destroy: true is set, passing _destroy: '1' in nested attributes deletes the child record. So the task with id 10 is removed from the database and does not appear in the remaining tasks.
Which is the best explanation for why Rails provides accepts_nested_attributes_for to handle nested attributes?
Think about the developer experience when working with forms that include related data.
accepts_nested_attributes_for allows a parent model to accept attributes for its associated child models in one form submission. This reduces the need for separate manual handling of child records, making code simpler and less error-prone. It does not automatically validate children or enforce database constraints, nor does it replace callbacks.