user-friendly unique records

Hey everybody,

  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 model
should check to see if it is exactly the same as an existing address, and if
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:

  def save
    if old_record = this_is_a_duplicate_record
      this.id = old_record.id
      this.reload
    else
      super
    end
  end

  ... is this the way to do it? Or is there a better/safer method?

  Thanks,
    Tyler

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
address.

I'm thinking something like:

Address < ActiveRecord::Base
  belongs_to :user

  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 ]
end

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
model layer.