在注册时验证用户的出生日期,但不能在Ruby on Rails中登录Facebook和Google

时间:2016-05-14 14:42:14

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我想检查18岁以上的出生日期。

如果我验证它,那么Facebook和Google登录无效。

如果我退出验证,那么电子邮件注册用户可以在不输入出生日期的情况下进行注册。我该怎么办?

我的 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

如果我在validates_date之前删除#,则Facebook和Google登录无法正常工作。是否有另一种方法来验证注册用户的出生日期?

1 个答案:

答案 0 :(得分:2)

您可以使用if选项进行验证:

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