Rails 7.1: How to handle custom validations in forms with nested attributes?
I'm stuck trying to I've been banging my head against this for hours... I've searched everywhere and can't find a clear answer. I'm working on a Rails 7.1 application where I have a `Project` model that accepts nested attributes for `Task`... I want to implement custom validations on the `Task` model to ensure that each task has a unique name within the same project. However, I run into issues where the validation fails even when the names are unique, likely due to the way the form is structured. I have the following form setup: ```erb <%= form_with model: @project do |f| %> <%= f.fields_for :tasks do |task_fields| %> <%= task_fields.label :name %> <%= task_fields.text_field :name %> <%= task_fields.error_message_on :name %> <% end %> <%= f.submit 'Save' %> <% end %> ``` In my `Task` model, I have implemented the validation as follows: ```ruby class Task < ApplicationRecord belongs_to :project validates :name, presence: true validate :unique_name_in_project private def unique_name_in_project if project && project.tasks.where.not(id: id).exists?(name: name) errors.add(:name, 'must be unique within the project') end end end ``` When I attempt to submit the form with two tasks named "Design" within the same project, the validation doesnβt seem to work as expected. Instead of only flagging the duplicate, it is raising errors even if they are distinct. Iβve confirmed that the `project` association is being set correctly in the controller: ```ruby def create @project = Project.new(project_params) if @project.save redirect_to @project else render :new end end ``` I also tried debugging the scenario by adding some logging inside the `unique_name_in_project` method, and it consistently returns true even when it should not. Additionally, I noticed that the `id` attribute of the `Task` instances might not be set when validations are being called since I use nested attributes and they haven't been persisted yet. How can I effectively validate uniqueness of task names within a project during the form submission, given this context? I'd really appreciate any guidance on this. What am I doing wrong? This is part of a larger microservice I'm building. Has anyone dealt with something similar? This is part of a larger REST API I'm building. Is this even possible?