validates的条件验证(if)的Proc用法

本文介绍了一个认证系统的实现方式,包括数据库结构、验证逻辑及用户邀请流程。重点讲解了针对不同认证方式(如电子邮件和电话号码)的处理方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实例:

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, or if: Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to a true or false value.

也就是条件if是对Authentication的实例对象也就是Proc传入的auth的provider字段进行验证

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值