Use of validates_uniqueness_of for create but not for edit

Hello People,

I wanted to validate my form for duplicate entries while creating a new
user . So I added validates_uniqueness_of in the users model. But it
gets applied to the edit user code also.

Since its an edit-user page, it should not validate duplicate records
and should update the existing record.Or say , is should have
validations of it own

I tried adding a validation function check_duplicate in the model and
called it before_create . But that gives errors.

Can anyone please help me for this.

Thanks n Regards

validates_uniqueness_of should validate on create and update, to achieve
some degree of uniqueness. Assuming your data is unique, am surprised
that your model is complaining.

Yukti Vig wrote:

Thanks Bl Jj for putting your time.

  before_create :check_duplicate

  def check_duplicate
    validates_uniqueness_of :login,:scope =>[:email], :case_sensitive
=> false
  end

This is what I added to my model. Amd the error I get is

undefined method `validates_uniqueness_of' for #<User:0x3752c24>

Is there any issue with the "check_duplicate" not getting values of
login and email.

regards.

Bl Jj wrote:

I don’t know if you can use the validates_* methods in callbacks, so I don’t know whether it makes sense for you to have received that error.

My first instinct would be to try something like

validates_uniqueness_of :login, :on => :create, …

The TextMate snippet for validates_uniqueness_of adds an :on option, but the Rails API docs don’t list one. I don’t have time to actually try it all out here, but maybe you can use the :on option to indicate that the check should be made only on :create.

Regards,
Craig

Hi,

The reason you're getting this error is because the "validates"
functions are class level methods, whereas your check_duplicate function
is an instance method. So, to fix this, just reference the "validates_"
methods with the appropriate model name:

def check_duplicate
  User.validates_uniqueness_of :login,:scope =>[:email], :case_sensitive
end

Craig Demyanovich wrote: