Zipcode , to_i and leading zero in Ruby/Rails

后端 未结 3 732
旧巷少年郎
旧巷少年郎 2021-01-14 13:14

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

相关标签:
3条回答
  • 2021-01-14 13:55

    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

    0 讨论(0)
  • 2021-01-14 13:58

    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.

    0 讨论(0)
  • 2021-01-14 14:05

    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.

    0 讨论(0)
提交回复
热议问题