Nested attributes let you save data for related models in one form. It helps keep things simple when models are connected.
0
0
Nested attributes in Ruby on Rails
Introduction
You want to create or update a parent record and its child records together.
You have a form where users can add details for multiple related items at once.
You want to manage a list of related objects inside a single form.
You want to avoid writing separate forms and actions for each related model.
Syntax
Ruby on Rails
class ParentModel < ApplicationRecord
has_many :child_models
accepts_nested_attributes_for :child_models
endUse accepts_nested_attributes_for in the parent model to allow nested data.
Rails will handle saving or updating the child models automatically.
Examples
This lets you create or update a book and its chapters in one go.
Ruby on Rails
class Book < ApplicationRecord
has_many :chapters
accepts_nested_attributes_for :chapters
endUse nested attributes for a one-to-one relation like author and profile.
Ruby on Rails
class Author < ApplicationRecord
has_one :profile
accepts_nested_attributes_for :profile
endAdding
allow_destroy: true lets you delete child records through the form.Ruby on Rails
class Project < ApplicationRecord
has_many :tasks
accepts_nested_attributes_for :tasks, allow_destroy: true
endSample Program
This example shows a Library model with many Books. The form sends nested book data inside the library data. The controller permits nested attributes and saves all together.
Ruby on Rails
class Library < ApplicationRecord has_many :books accepts_nested_attributes_for :books end # In controller class LibrariesController < ApplicationController def new @library = Library.new @library.books.build end def create @library = Library.new(library_params) if @library.save redirect_to @library else render :new end end private def library_params params.require(:library).permit(:name, books_attributes: [:title, :author]) end end # Example params from form: # { # library: { # name: "City Library", # books_attributes: { # "0" => { title: "Ruby Basics", author: "Jane" }, # "1" => { title: "Rails Guide", author: "John" } # } # } # }
OutputSuccess
Important Notes
Remember to permit nested attributes in the controller using permit.
Use build to prepare nested objects for the form.
Nested attributes work best for simple related data, not very complex associations.
Summary
Nested attributes let you save parent and child models together.
Use accepts_nested_attributes_for in the parent model.
Permit nested params in the controller to allow saving related data.