I have 3 models as follows:
class Document < ActiveRecord::Base
has_many :documents_tasks, inverse_of: :document
has_many :tasks, through: :documents_tasks, dependent: :destroy
end
class Task < ActiveRecord::Base
has_many :documents_tasks, inverse_of: :task
has_many :documents, through: :documents_tasks, dependent: :destroy
end
class DocumentsTask < ActiveRecord::Base
belongs_to :task, inverse_of: :documents_tasks
belongs_to :document, inverse_of: :documents_tasks
validates_uniqueness_of :document_id, scope: :task_id
end
In the above when I try to update the record for a Task
it throws a validation error for duplicate entries on the DocumentsTask
model if I keep the validation or directly inserts duplicates if remove the validation.
My code to update the Task record is:
def update
@task = @coach.tasks.find(params[:id])
@task.update(:name => task_params[:name], :description => task_params[:description] )
@task.documents << Document.find(task_params[:documents])
if @task.save
render 'show'
else
render status: 500, json: {
error: true,
reason: @task.errors.full_messages.to_sentence
}
end
end
I know I can add unique index
to the db to automatically prevent duplicate entries but is there some way I can prevent the controller
from updating the join table values when they're the same?
So when I attempt to update the associated documents, ex:
- I had document 5 initially
- Now I add document 6 and call the update function
It attempts to re-add both documents 5 and 6 to the db so I get the error:
Completed 422 Unprocessable Entity in 9176ms
ActiveRecord::RecordInvalid (Validation failed: Document has already been taken)
This is because I added the following validation:
validates_uniqueness_of :document_id, scope: :task_id
in my DocumentsTask model as shown above. The issue is how can I prevent it from attempting to re-add existing records