Forum: Ruby on Rails validates_uniqueness_of only if present

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
dino d. (Guest)
on 2008-11-19 13:42
(Received via mailing list)
Hi - I want to allow duplicate fields values if the field is blank,
but disallow duplicates if it's not.  Is there a
validates_uniqueness_of_if_present equivalent?

Thanks,
Dino
Thorsten M. (Guest)
on 2008-11-19 13:54
(Received via mailing list)
You can use :allow_nil or :allow_blank attributes to it like

validates_uniqueness_of :email, :allow_nil => true

this would skip the validation if field is nil.
:allow_blank works same way on empty strings.

And then all/most validations com with the :if and :unless options
that would allow for more detailed determination if the validation
should be used
Priyanka P. (Guest)
on 2008-11-19 14:09
dino d. wrote:
> Hi - I want to allow duplicate fields values if the field is blank,
> but disallow duplicates if it's not.  Is there a
> validates_uniqueness_of_if_present equivalent?
>
> Thanks,
> Dino

Hi,
   As you required to place duplicate value if field is blank than you
just use
   validates_uniqueness_of :field_name,:allow_blank => 'true'

   :allow_nil - If set to true, skips this validation if the attribute
is nil  (default is false).

   :allow_blank - If set to true, skips this validation if the attribute
is blank (default is false).
This topic is locked and can not be replied to.