CodexBloom - Programming Q&A Platform

Rails 7.1: implementing Custom Validation on Nested Attributes Not Triggering

πŸ‘€ Views: 1636 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
ruby-on-rails validation nested-attributes Ruby

I've been banging my head against this for hours... I'm working with an scenario with custom validations on nested attributes in Rails 7.1. My model setup involves a `Project` that `has_many :tasks`, and I want to ensure that each `task` has a unique name within the context of its `project`. I've set up the nested forms correctly, but the custom validation method isn't being triggered as expected when I submit the form. Here’s a simplified version of my models: ```ruby class Project < ApplicationRecord has_many :tasks, dependent: :destroy accepts_nested_attributes_for :tasks, allow_destroy: true end class Task < ApplicationRecord belongs_to :project validate :unique_name_within_project private def unique_name_within_project if project.tasks.where(name: name).exists? errors.add(:name, 'must be unique within this project') end end end ``` In my form, I'm using fields_for to handle the tasks: ```erb <%= form_with(model: @project) do |f| <%= f.fields_for :tasks do |task_fields| %> <%= task_fields.text_field :name %> <%= task_fields.hidden_field :_destroy %> <% end %> <%= f.submit %> <% end %> ``` When I submit the form with duplicate task names, I see the behavior messages on other validation errors but not for the unique name check. I’ve tried debugging by adding some `puts` statements within the `unique_name_within_project` method, and they show that the method is not being called. I've confirmed that the nested attributes are being saved correctly. I’ve also tried moving the validation to the `Project` model to validate the `tasks` after building them, but that led to different issues where the validation only checks tasks already saved in the database instead of the ones being validated in the form. Is there a best practice for triggering custom validations on nested attributes in this scenario? Any insights would be greatly appreciated! I'm working on a web app that needs to handle this.