Rails 7.1: advanced patterns when using custom validations in nested forms
I'm migrating some code and I'm working on a project and hit a roadblock... I'm working with an scenario with custom validations in my Rails 7.1 application when dealing with nested forms. I have a `Project` model that has_many `Tasks`, and each `Task` has a custom validation that checks whether the `title` is unique within the scope of its associated `Project`. However, when I submit the nested form, I receive a validation behavior even though I believe the titles are unique. Hereβs a simplified version of my models: ```ruby class Project < ApplicationRecord has_many :tasks, inverse_of: :project accepts_nested_attributes_for :tasks, reject_if: :all_blank end class Task < ApplicationRecord belongs_to :project validates :title, presence: true validate :unique_title_within_project def unique_title_within_project if project.tasks.where(title: title).exists? errors.add(:title, 'must be unique within this project') end end end ``` In my form view, I'm rendering the nested attributes like this: ```erb <%= form_with model: @project do |f| %> <%= f.fields_for :tasks do |task_fields| %> <%= task_fields.text_field :title %> <%= task_fields.error_message_on :title %> <% end %> <%= f.submit 'Save' %> <% end %> ``` When I test this, if I create a project with a task titled 'Design', and then try to add another task with the same title 'Design' in the nested form, I receive the expected validation behavior. However, if I edit the first task to 'Design' and then attempt to submit the form again without changing the title of the second task, I still get a validation behavior as if itβs treating the titles as duplicates. I've tried debugging by adding some logging inside the `unique_title_within_project` method, and it shows that the query is checking against the titles as expected, but I need to figure out why it fails. Has anyone faced a similar scenario or have insights on how to correctly implement this validation while allowing for the same title in existing tasks? This is part of a larger web app I'm building. What am I doing wrong? This is my first time working with Ruby 3.11. I'd be grateful for any help.