How to set up a nested form in Ruby on Rails

suggest change

Start with a model that has_many of another model. accepts_nested_attributes_for is what lets the parent save the children from one form.

class Project < ApplicationRecord
  has_many :todos
  accepts_nested_attributes_for :todos
end

class Todo < ApplicationRecord
  belongs_to :project
end

In ProjectsController, build a child so the form has something to edit:

class ProjectsController < ApplicationController
  def new
    @project = Project.new
    @project.todos.build
  end
end

A nested form creates the child records with the parent. Rails uses form_for (or form_with) and fields_for. nested_form_for is not a Rails method; it comes from the nested_form gem. The association name is :todos, matching has_many :todos.

<%= form_for @project do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= f.fields_for :todos do |todo_field| %>
    <%= todo_field.label :name %>
    <%= todo_field.text_field :name %>
  <% end %>
<% end %>

fields_for :todos renders nothing until the association has objects. Building them in new, as above, is the usual approach. You can also build in the view with f.fields_for :todos, @project.todos.build, which adds another unsaved todo on every render.

Permit the nested attributes. The key is todos_attributes, not todo_attributes:

def project_params
  params.require(:project).permit(:name, todos_attributes: [:name])
end

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents