Using validates_uniqueness_of with :update

Hi,

I need to use validates_uniqueness_of only when inserting new records but not when update them.

I use the following line of code,

validates_uniqueness_of :type_id, :scope => [:user_name], :unless => :update, :message => "This has already been registered"

But still it doesn't run validations and allow duplicate inserts.

Thanks in advance for your feedback.

BR,

Shiran

Hi,

I need to use validates_uniqueness_of only when inserting new records but not when update them.

I use the following line of code,

validates_uniqueness_of :type_id, :scope => [:user_name], :unless => :update, :message => "This has already been registered"

But still it doesn't run validations and allow duplicate inserts.

Looks like you're confusing the :unless/:if options (which take a method name or block and run the validation depending on whether the block/method evaluates to true) and the :on option.

Fred

validates_uniqueness_of :type_id, :scope => [:user_name], :message => "This has already been registered", :if => :new_record?

Thanks Fred... will look at it

Thanks a lot Sharagoz...

Hi,

    As you need to fire uniqueness validation during creation of new record.

validates_uniqueness_of :type_id, :scope => [:user_name],:on => :create, :message => "This has already been registered"

Thanks Priyanka...

Another technique which may be overkill for what you need is doing something like this…

Say you have a very simple user signup but, after signup they have to fill in a more extensive user profile which has many more fields. I’ve solved this by doing:

class User < ActiveRecord::Base

validates_presence_of :login, :email

validates_presence_of :password, :unless => :password_set

validates_presence_of :password_confirm, :unless => :password_set

validates_length_of :password, :within => 4…40, :unless => :password_set

validates_confirmation_of :password, :unless => :password_set

validates_length_of :login, :within => 3…40

validates_length_of :email, :within => 3…100

validates_uniqueness_of :login, :email, :case_sensitive => false

validates_as_email :email

end

This handles the User Form validations

class UserForm < User

validates_presence_of :first_name

validates_presence_of :last_name

end

When doing things that require first, last name just use the UserForm object instead.