Search code examples
ruby-on-railsvalidationruby-on-rails-4deviseomniauth

Devise Omniauth-facebook bypass rails validations


I just followed this article to implement omniauth in my rails 4 app.

In my User model, I have two types of users, namely ADMIN(created by form) and MEMBER(created by omniauth). I need to bypass ALL the validations for MEMBER user who will be created by omniauth.

I know that this could be done by passing this option:

save(validate: false)

However, first_or_create method was adopted:

  def self.from_omniauth(auth)
    # where(auth.slice(:provider, :uid)).first_or_create do |user|
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.email = auth.info.email
      user.password = Devise.friendly_token[0,20]
      user.name = auth.info.name   # assuming the user model has a name
      user.image = auth.info.image # assuming the user model has an image
    end
  end

So, my question is: How do I bypass ALL the validations in this omniauth case?

Please advise.


Solution

  • first_or_create doesn't seem to take any options, but you still have a couple options.

    Instead of first_or_create, you could do first_or_initialize, which works the same as first_or_create but doesn't save. You would then have a new record that you could call save(validate: false) on

    But, then you'd have records in the system that aren't valid, so if you go to update one of these records' emails, for instance, you would have to get around the validations again.

    What I would suggest is moving this logic to the validations themselves:

    validate_presence_of :name, unless: -> { from_omniauth? }
    
    private
    
    def from_omniauth?
      provider && uid
    end