Rails 7.1: How to resolve `undefined method 'name' for nil:NilClass` when trying to access a nested attribute in a form?
I'm sure I'm missing something obvious here, but I'm relatively new to this, so bear with me. I'm trying to configure I'm encountering a frustrating issue with nested attributes in Rails 7.1. I'm attempting to create a form for a `Project` that has many `Tasks`. The form should allow me to add a project name and a list of tasks with each task having its own name. Iโve set up the associations correctly, but when I submit the form, I receive an `undefined method 'name' for nil:NilClass` error. Hereโs a simplified version of the relevant parts of my code: **Model Setup:** ```ruby class Project < ApplicationRecord has_many :tasks, dependent: :destroy accepts_nested_attributes_for :tasks, allow_destroy: true end class Task < ApplicationRecord belongs_to :project end ``` **Form Code:** ```erb <%= form_with model: @project do |f| %> <%= f.label :name %> <%= f.text_field :name %> <%= f.fields_for :tasks do |task_fields| %> <%= task_fields.label :name %> <%= task_fields.text_field :name %> <% end %> <%= f.submit 'Create Project' %> <% end %> ``` **Controller:** ```ruby class ProjectsController < ApplicationController def new @project = Project.new @project.tasks.build # This line is crucial to initialize a task end def create @project = Project.new(project_params) if @project.save redirect_to @project, notice: 'Project was successfully created.' else render :new end end private def project_params params.require(:project).permit(:name, tasks_attributes: [:id, :name, :_destroy]) end end ``` Iโve verified that the project is indeed created without any tasks, but I still get the error when I try to access the form. The error seems to occur when the form attempts to render the fields for the tasks, and I suspect it might be due to the `fields_for` not having a `Task` object to work with. Iโve also tried initializing multiple tasks in the `new` method like `@project.tasks.build` multiple times, but that did not help. Any insights on how to fix this issue or best practices around using nested attributes with forms in Rails would be greatly appreciated. The project is a mobile app built with Ruby. Thanks for taking the time to read this! My team is using Ruby for this application. I recently upgraded to Ruby LTS.