Mathieu
Mathieu

Reputation: 4787

How to properly write in Ruby a validate only on create

I have now this validate for my User model:

validates :email,
            presence: true,
            uniqueness: { :case_sensitive => false }

I'd like to add :on create for the uniqueness as users are definitely allowed to update their email by putting the same email!

Should I write it this way? I'm afraid the on:create also applies to the presence:true but it should only apply to the uniqueness validation:

validates :email,
             presence: true,
             uniqueness: { :case_sensitive => false }, on: :create

Upvotes: 1

Views: 65

Answers (2)

Bachan Smruty
Bachan Smruty

Reputation: 5734

I would like to say some logic. Email should be unique and user will be identified by his email. So while update, there is no need to put email field where user can edit the email value. You can make the email field as readonly, so that user can not change it while updating the profile.

And yes, the syntax on: :create is the nice solution for it.

Upvotes: 1

Nitin Jain
Nitin Jain

Reputation: 3083

yes it will applied on both you can use separate validation for that

validates :email,  presence: true

validates :email, uniqueness: { :case_sensitive => false }, on: :create

Upvotes: 1

Related Questions