Ruby on Rails 4例外:如果字段为空,如何绕过

Nub*_*lar 1 validation ruby-on-rails twilio

我的Subscription模型有一个表单,用户可以选择输入电话号码.正在使用Twilio API.

class Subscription < ActiveRecord::Base

    validates_numericality_of :phone_number, allow_blank: true
    validate :mobile_phone_number

    def mobile_phone_number
        lookup_client = Twilio::REST::LookupsClient.new Rails.application.secrets.twilio_sid, Rails.application.secrets.twilio_token
        begin
            response = lookup_client.phone_numbers.get("#{self.phone_number}")
            response.phone_number #if invalid, throws an exception. If valid, no problems.
            return true
        rescue => e
            errors.add(:base, "That phone number is not valid.")
        end
    end
Run Code Online (Sandbox Code Playgroud)

发生了什么:我只能输入有效的电话号码给定Twilio查找API ...这是一件好事.但是,用户需要能够输入BLANK电话号码.

目前,该validates_numericality_of方法正在被该mobile_phone_number方法覆盖.

如果我输入空白的phone_number,则返回"该电话号码无效".这不应该发生.

我该怎么做一个特例rescue呢?例如,"除非电话号码为空,否则将其解救".或者我在这里做错了什么?

所有输入都表示赞赏.

Aza*_*ine 6

这样您甚至不会输入验证功能.看看条件验证

validate :mobile_phone_number, unless: proc { phone_number.blank? }
Run Code Online (Sandbox Code Playgroud)

对于那些不喜欢的人

validate :mobile_phone_number, if: proc { phone_number.present? }
Run Code Online (Sandbox Code Playgroud)