实例:
authentication.rb中
# == Schema Information
#
# Table name: authentications
#
# id :integer not null, primary key
# user_id :integer not null
# provider :string(255) not null
# uid :string(255) not null
# created_at :datetime
# updated_at :datetime
# country_code :string(255)
#
class Authentication < ActiveRecord::Base
belongs_to :user
scope :email_auth, -> {where(provider: "email")}
scope :phone_auth, -> {where(provider: "phone")}
validates :uid, format: /@/, if: Proc.new { |auth| auth.provider == "email" }
after_create :accept_invitation
def accept_invitation
if provider == 'phone'
if @invitation = Invitation.where(status: 'not_registered', country_code: country_code, phone_number: uid).first
@invitation.update(user_id: user_id, status: 'registered')
PointRecord.point_for_accept_invitation(user, @invitation)
end
end
end
def self.phone_register?(phone, country_code = "+86")
Authentication.find_by(provider: "phone", uid: phone, country_code: country_code).present?
end
def self.email_register?(email)
Authentication.find_by(provider: "email", uid: email)
end
end
****************validates :uid, format: /@/, if: Proc.new { |auth| auth.provider == "email" }
注意这一句:
官方文档解释是
-
:if
- Specifies a method, proc or string to call to determine if the validation should occur (e.g.if: :allow_validation
, orif: Proc.new { |user| user.signup_step > 2 }
). The method, proc or string should return or evaluate to atrue
orfalse
value.