我有一个表格,用于我的Subscription
模型,用户可以选择输入电话号码。 Twilio API正在使用中。Ruby on Rails 4例外:如果字段为空,如何绕过
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
什么发生:我只能输入有效的电话号码给Twilio查找API ...这是一件好事。但是,用户需要能够输入一个BLANK电话号码。
目前,validates_numericality_of
方法正在被mobile_phone_number
方法覆盖。
如果输入空白phone_number,则返回“该电话号码无效”。这不应该发生。
如何为rescue
制作特例?例如,“救救这个,除非电话号码是空白的”。或者我在这里做错了什么?
所有的输入赞赏。
'验证:MOBILE_PHONE_NUMBER,如果: “phone_number.present”' – devanand
可以和红宝石定义为方法'高清method_name rescue end'(多行看起来会更好)并且拯救特定的错误,所以不需要在方法内部开始/救援/结束块。 – Kocur4d