CodexBloom - Programming Q&A Platform

Rails 7.1: Difficulty preventing duplicate records when using nested attributes in form submission

👀 Views: 148 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
ruby-on-rails active-record nested-attributes ruby

I'm converting an old project and I'm trying to figure out I've searched everywhere and can't find a clear answer... I'm trying to implement I'm having trouble preventing duplicate records in my Rails 7.1 application when using nested attributes in a form. I have a `Project` model that has many `Tasks`, and I'm allowing users to create multiple tasks at once through a form. However, when the form is submitted, I notice that duplicate tasks are being created if the user accidentally submits the form multiple times or if the same task details are entered. I tried using `validates_uniqueness_of` on the `Task` model, but it doesn't seem to work as expected when nested attributes are involved. Here's a snippet of my `Project` model: ```ruby class Project < ApplicationRecord has_many :tasks, dependent: :destroy accepts_nested_attributes_for :tasks, allow_destroy: true end ``` And my `Task` model looks like this: ```ruby class Task < ApplicationRecord belongs_to :project validates :name, presence: true, uniqueness: { scope: :project_id } end ``` In my form, I have something like this: ```erb <%= form_with model: @project do |f| %> <%= f.fields_for :tasks do |task_fields| %> <div class="task-fields"> <%= task_fields.text_field :name %> <%= task_fields.check_box :_destroy %> </div> <% end %> <%= f.submit %> <% end %> ``` I also tried wrapping the creation logic in a transaction, but it doesn't seem to prevent duplicates if the same task is submitted multiple times. I get the following error when duplicates are attempted: ``` ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "tasks_project_id_name_key" ``` Is there a way to handle this more gracefully? Any suggestions to prevent duplicates without compromising user experience or database integrity would be appreciated! I'm coming from a different tech stack and learning Ruby. Thanks in advance! This is happening in both development and production on Linux. Has anyone dealt with something similar? Any examples would be super helpful.