MSK MSK - 6 months ago 33
Ruby Question

Validate user's date of birth while registering, but not for Facebook and Google login in Ruby on Rails

I want to check the condition for date of birth above 18.

If I validate it then Facebook and Google logins are not working.

If i leave the validation, then email registered users are able to register without entering date of birth. How can I do it ?

My user.rb,

class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: [:google_oauth2, :facebook]

validates :fullname, presence: true, length: {maximum: 40}
validates :password, :format => { :with => /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/, :message => "Password should contain at least 6 characters, one upper case, one lower case and one numeric." }, on: :create validates :password, :format => { :with => /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/, :message => "Password should contain at least 6 characters, one upper case, one lower case and one numeric." }, on: :update, allow_blank: true

#validates_date :date_of_birth, :before => lambda { 18.years.ago },
# :before_message => "must be at least 18 years old"

has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100#" }
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/

def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.fullname = auth.info.name
user.provider = auth.provider
user.uid = auth.uid
user.email = auth.info.email
user.image = auth.info.image
user.password = Devise.friendly_token[0,20]
end
end

end


If I delete the # before validates_date then Facebook and Google logins are not working. Is there another way to validate the date of birth for registering the user ?

Answer

You can use the if option for validation:

validates_date :date_of_birth, :before => lambda { 18.years.ago },
                           :before_message => "must be at least 18 years old",
                if: :validate_date_of_birth?

def validate_date_of_birth?
  !(provider == 'google' || provider == 'fb')
end