Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

text_field eating leading zero strings

#1610

Hi,

I have an issue where users must be able to set their postal code. We've set postal code to be a 5 length string. If we're using :

<%= form.text_field :postal_code, :size => 10 %>

The postal code is always displayed with leading zeros missing, even if the value is right in irb (user.postal_code => "02456" will be displayed "2456")

We changed our code to

<%= text_field_tag 'user[postal_code]', @user.postal_code, :size => 5, :maxlength => 5 %>

and now the leading zeros are there.

By the way, we had to override the method in user model to display the value correctly :

def postal_code
  read_attribute(:postal_code).to_s.rjust(5,"0")     
end

So, not sure if it's a real bug, or a ActionView nor ActiveRecord bug.

Thanks, Phil

Reported by Gravis · December 20th, 2008 @ 10:28 PM

State: invalid
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Frederick Cheung
    Frederick Cheung

    That's weird - I tried this on edge and 2.2.2 and it seem to work fine. What version of rails were you using.

    December 21st, 2008 @ 04:39 PM

  2. Gravis
    Gravis

    Hi,

    I'm using rails 2.2.2, and the site has been migrated several time from 1.X.

    The column type is a string, in schema.rb :

    t.string   "postal_code"
    
    

    and the problem occurs using sqlite and mysql.

    Thanks

    December 21st, 2008 @ 08:45 PM

  3. Gravis
    Gravis

    can't reproduce problem on a fresh 2.2.2 app.

    Okkkk, really sorry, my fault, the field was indeed an integer, and not a string (we have 2 postal codes there).

    We can close the ticket, and really sorry for the time spend :(

    December 21st, 2008 @ 11:36 PM

  4. Yehuda Katz (wycats)
    Yehuda Katz (wycats)
    • State changed from new to invalid

    Gravis: no need to apologize! Is there anything we can do in documentation to reduce the possibility of someone else experiencing this same issue?

    December 24th, 2008 @ 08:12 AM

  5. Gravis
    Gravis

    Thanks Yehuda !

    I think just a little paragraph in the guides explain that fields with possible leading zeros like postal codes, phone numbers, etc should be stored as string (with a :limit if possible). Also, It's generally a good idea to store this large "numbers" in a string field, since we generally don't do any calculation on them, nor number comparison ("postal code > value" ?). I'll try to add some lines in the rails guides regarding that.

    Thanks Gravis (hope this post won't re-open the ticket !)

    December 24th, 2008 @ 10:18 AM