Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - how to skip validation rule?

I have for the registration form this validation rule:

  validates :email, 
    :presence => {:message => 'cannot be blank.'}, 
    :allow_blank => true, 
    :format => {
      :with => /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/, 
      :message => 'address is not valid. Please, fix it.'
    }, 
    :uniqueness => true

This rule check, if a user fill into the registration form email address (+ its correct format).

Now I am trying to add the opportunity to log in with using Twitter. Twitter doesn't provide user's email address.

How to skip in this case the validation rule above?

like image 365
user984621 Avatar asked Sep 30 '12 12:09

user984621


2 Answers

You can skip validation while saving the user in your code. Instead of using user.save!, use user.save(:validate => false). Learnt this trick from Railscasts episode on Omniauth

like image 147
Prakash Murthy Avatar answered Oct 17 '22 12:10

Prakash Murthy


I'm not sure whether my answer is correct, just trying to help.

I think you can take help from this question. If i modify the accepted answer for your question, it will be like (DISCLAIMER: I could not test the following codes as env is not ready in the computer i'm working now)

validates :email, 
  :presence => {:message => 'cannot be blank.', :if => :email_required? },
  :allow_blank => true, 
  :format => {
    :with => /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/, 
    :message => 'address is not valid. Please, fix it.'
  },
  :uniqueness => true

def email_required?
  #logic here
end

Now, you update the email_required? method to determine whether it is from twitter or not! If from twitter, return false otherwise true.

I believe, you need use same :if for the :uniqueness validator too. otherwise it will. Though, i'm not sure too :(. Sorry

like image 37
HungryCoder Avatar answered Oct 17 '22 10:10

HungryCoder