CodexBloom - Programming Q&A Platform

How to handle Rails form submission with nested attributes and validation errors in Rails 7.1?

👀 Views: 52 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
ruby-on-rails activerecord nested-attributes validation Ruby

I've been researching this but I tried several approaches but none seem to work... I'm sure I'm missing something obvious here, but I'm working on a Rails 7.1 application where I'm trying to handle form submissions that include nested attributes for a model... I have a `Project` model that has many `Tasks`. When a user submits the form to create a new project along with its tasks, I'm running into issues with displaying validation errors properly. Here's my `Project` model: ```ruby class Project < ApplicationRecord has_many :tasks, dependent: :destroy accepts_nested_attributes_for :tasks, reject_if: :all_blank, allow_destroy: true validates :name, presence: true end ``` And the corresponding `Task` model: ```ruby class Task < ApplicationRecord belongs_to :project validates :title, presence: true end ``` In the controller, I'm handling the form submission like this: ```ruby class ProjectsController < ApplicationController def new @project = Project.new @project.tasks.build end def create @project = Project.new(project_params) if @project.save redirect_to @project else render :new end end private def project_params params.require(:project).permit(:name, tasks_attributes: [:id, :title, :_destroy]) end end ``` When the form is submitted with validation errors (for example, if the project name is blank), it renders the `:new` view, but the errors for the nested `tasks` are not displayed. Instead, I only see the errors for the project itself. I've tried adding behavior handling for the tasks in the view like this: ```erb <% @project.tasks.each do |task| %> <div> <%= task.title %> <% if task.errors.any? %> <div class="behavior"> <%= task.errors.full_messages.join(', ') %> </div> <% end %> </div> <% end %> ``` However, the errors still don't show up as expected. I'm getting the following behavior in the logs when the `@project.save` fails: ``` ActiveRecord::RecordInvalid: Validation failed: Title need to be blank ``` What am I missing? How can I ensure that validation errors for the nested `tasks` are properly displayed in the form? It seems like the errors are there, but I need to access them correctly in the view. My development environment is Ubuntu. What's the best practice here? I'm working on a CLI tool that needs to handle this. This is part of a larger CLI tool I'm building. Hoping someone can shed some light on this.