I’ve got a table that contains addresses. Addresses belong_to users.
When a new address is added, I would like to avoid duplicates. The
should check to see if it is exactly the same as an existing address,
it is, instead of saving the address and returning a new record, I would
like it to load the old record.
I’m thinking something like this:
if old_record = this_is_a_duplicate_record
this.id = old_record.id
… is this the way to do it? Or is there a better/safer method?
Personally, I think that’s a bad idea. Overriding the behavior of
save seems rather dangerous and confusing. The save method should
either return true or false (indicating validation or database errors
encountered during save). It should not attempt to return an instance
of some other object.
Instead you should allow the normal validation system to provide
feedback to the user that they are attempting to insert a duplicate
I’m thinking something like:
Address < ActiveRecord::Base
validate_uniqueness_of :address, :scope =>
[ :user_id, :city, :state, :zip ]
validate_uniqueness_of :city, :scope =>
[ :user_id, :address, :state, :zip ]
validate_uniqueness_of :state, :scope =>
[ :user_id, :address, :city, :zip ]
validate_uniqueness_of :zip, :scope =>
[ :user_id, :address, :city, :state ]
Now in your controller/view you could then provide them a link or
possibly redirect to some view of the user showing the existing
address. But, this type of thing should not happen anywhere in the