简体   繁体   中英

Zipcode , to_i and leading zero in Ruby/Rails

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.

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"

It makes conceptually no sense to have a leading 0 when talking about an integer. Either format the zipcode when you use it (ie. make sure it has the right format, add a leading 0 when converting from int to str), or save it as a string

将其保存为字符串将减轻该问题,并且如果您决定支持可能有也可能没有字母的外国邮政编码,这也将有助于面向未来的事情。

Yeah, I agree that it doesn't make sense to store zips as integers for just this reason. I also think you need to be very sure that you won't ever need non-US postal codes in your app. With those caveats out of the way, though...

If you are unable to modify the database for some reason, you can modify the get method for the zip code, like so:

def zip
  val = read_attribute(:zip).to_s
  val.length < 5 ? add_leading_zeros(val) : val
end

def add_leading_zeros(val)
  while val.length < 5 do
    val = "0" + val.to_s
  end
  val
end

It's kind of hacky, and I really don't recommend doing it this way if you can modify the DB field to be a string (varchar).

You might also want to modify the validation that you're using, as it will allow zip codes of less than 5 characters through.

Maybe use something like this:

validates_format_of :zip, :with => /^\d{5}$/

EDIT: I'll leave this answer here, but I just noticed that the OP already changed the field type in the DB... So, yeah, I feel a little silly for having typed all of this now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM