Forum: Ruby on Rails user-friendly unique records

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
52cb4115a870ff1942e7e1ae96f4306f?d=identicon&s=25 Tyler MacDonald (Guest)
on 2007-06-05 22:14
(Received via mailing list)
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
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 =

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

21f7ed21f11a809050594c82eab11d67?d=identicon&s=25 Robert Walker (Guest)
on 2007-06-06 00:06
(Received via mailing list)
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
  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 ]

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.
This topic is locked and can not be replied to.