Reputation: 3398
I have a model with a uniqueness validation based on a scope (I'm using Rails 5):
validates_uniqueness_of :n_pacote, scope: :ecg_id
Even with that validation, I noticed that are duplicated n_pacote
values for a same ecg_id
. I also noticed that they were created almost at the same time:
[Thu, 05 Jul 2018 14:07:59 -03 -03:00, Thu, 05 Jul 2018 14:07:58 -03 -03:00, Thu, 05 Jul 2018 14:07:58 -03 -03:00]
They're created from an api call that may be called multiple times. How can I fix that? Thanks in advance
EDIT:
Here's all attributes for the 3 records that have the same n_pacote
value for the same ecg_id
:
{"id"=>32289, "ecg_id"=>29, "leitura"=>[170, 69, 85, 81, 69, 85, 81, 69, 85, 81, 70, 102, 98, 70, 102, 98, 70, 102, 98, 71, 119, 115, 71, 119, 115, 71, 119, 115, 72, 136, 132, 72, 136, 132, 72, 136, 132, 73, 153, 149, 73, 153, 149, 73, 153, 149], "posprocessada"=>nil, "created_at"=>Thu, 05 Jul 2018 14:07:59 -03 -03:00, "updated_at"=>Thu, 05 Jul 2018 14:07:59 -03 -03:00, "n_pacote"=>1620}
{"id"=>32276, "ecg_id"=>29, "leitura"=>[170, 69, 85, 81, 69, 85, 81, 69, 85, 81, 70, 102, 98, 70, 102, 98, 70, 102, 98, 71, 119, 115, 71, 119, 115, 71, 119, 115, 72, 136, 132, 72, 136, 132, 72, 136, 132, 73, 153, 149, 73, 153, 149, 73, 153, 149], "posprocessada"=>nil, "created_at"=>Thu, 05 Jul 2018 14:07:58 -03 -03:00, "updated_at"=>Thu, 05 Jul 2018 14:07:58 -03 -03:00, "n_pacote"=>1620}
{"id"=>32256, "ecg_id"=>29, "leitura"=>[170, 69, 85, 81, 69, 85, 81, 69, 85, 81, 70, 102, 98, 70, 102, 98, 70, 102, 98, 71, 119, 115, 71, 119, 115, 71, 119, 115, 72, 136, 132, 72, 136, 132, 72, 136, 132, 73, 153, 149, 73, 153, 149, 73, 153, 149], "posprocessada"=>nil, "created_at"=>Thu, 05 Jul 2018 14:07:58 -03 -03:00, "updated_at"=>Thu, 05 Jul 2018 14:07:58 -03 -03:00, "n_pacote"=>1620}
Upvotes: 0
Views: 281
Reputation: 169
I was facing similar issue but later I used db level uniqueness to avoid this one. Rails validation isn't 100% reliable when comes to uniqueness.
To be on safer side, add this validation on your db (MySQL ex).
add_index :table_name, [:n_pacote, :ecg_id], unique: true
Upvotes: 1