邮政编码、to_i 和 Ruby/Rails 中的前导零 [英] Zipcode , to_i and leading zero in Ruby/Rails
问题描述
我试图将在参数中传递的邮政编码保存为 "07306"
和 "03452"
,但 to_i
似乎在验证之前将这些字符串值转换为 7306
和 3452
,因此验证一直失败.
I am trying to save zip codes which are passed in the params as "07306"
, and "03452"
, but to_i
seems to be converting these string values to 7306
and 3452
before validation, because of which the validation keeps failing.
如何防止 Ruby 删除前导零?
How do I prevent Ruby from removing the leading zeros?
邮政编码是数据库中的一个整数字段,验证使用以下命令检查邮政编码:
The zip code is an integer field in the database and the validation checks for the format of the zip using:
validates_format_of :zip, :with => /\A[+\-]?\d+\Z/, :message => "Please enter a valid US zipcode"
推荐答案
将其另存为字符串将缓解该问题,并且如果您决定支持可能有也可能没有的外国邮政编码,也将有助于面向未来的事情其中的字母.
Saving it as a string instead will alleviate that issue, and also would help future-proof things if you decide to support foreign ZIP codes which may or may not have letters in them.
这篇关于邮政编码、to_i 和 Ruby/Rails 中的前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!