I got addresses hash. I am building addresses via nested attributes. If address hash is duplicate(i.e. address1, zip, country, city) combo already exists, then skip and go for next address hash and create. I want to write it in a model. Custom Validation will halt the execution. What is the other option to achieve the same
Asked
Active
Viewed 77 times
1
-
1add unique indexed on db level, catch the exception (ActiveRecord::RecordNotUnique) and handle it. – NeverBe Feb 05 '19 at 10:18
-
It sounds like you you need a [callback](https://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html) rather than an validation to handle this. – SRack Feb 05 '19 at 10:46
-
I know but I do not want the execution to be halted. I just want to ignore that hash – Radz Singh Feb 05 '19 at 10:46
-
I think, I should ignore the hash in a before_save callback – Radz Singh Feb 05 '19 at 10:47
-
Does this answer your question? [Validate uniqueness of multiple columns](https://stackoverflow.com/questions/4870961/validate-uniqueness-of-multiple-columns) – dre-hh Jul 18 '22 at 10:42
-
Also see https://stackoverflow.com/questions/4870961/validate-uniqueness-of-multiple-columns/29961501#29961501 – dre-hh Jul 18 '22 at 10:43
1 Answers
1
def insert_address_with_hash(hash)
Address.create!(hash)
rescue ActiveRecord::RecordNotUnique => e
puts 'Ignore dups'
end
and Migration (template)
class AddUniqIndexOnAdresses < ActiveRecord::Migration
def change
add_index :addresses, [:address1, :zip, :country, :city], :unique => true
end
end
Be sure you don't have nonunique rows in the table, the migration wont work.

NeverBe
- 5,213
- 2
- 25
- 39