Forum: Ruby on Rails form.text_field display of sql decimal

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
unknown (Guest)
on 2007-04-19 04:07
(Received via mailing list)
hey all,

I've got this column in a mysql table:
wholesale_price decimal(6,2)

this is the actual value that is currently stored in the db:
+-----------------+
| wholesale_price |
+-----------------+
|           19.00 |
+-----------------+

the the view code to edit that:
<%= form.text_field :wholesale_price %>

but then the rendered html source looks like this:
<input id="film_wholesale_price" name="film[wholesale_price]" size="5"
type="text" value="19.0" />

when I want it to look like this:
<input id="film_wholesale_price" name="film[wholesale_price]" size="5"
type="text" value="19.00" /> <-- note the extra "0"

I mucked around with creating a helper method to fix that up but seem
to be missing something simple/obvious.

Thanks in advance for any help!
Tim
Sh0Ck_filE (Guest)
on 2007-04-19 04:57
(Received via mailing list)
> but then the rendered html source looks like this:
> <input id="film_wholesale_price" name="film[wholesale_price]" size="5"
> type="text" value="19.0" />
>
> when I want it to look like this:
> <input id="film_wholesale_price" name="film[wholesale_price]" size="5"
> type="text" value="19.00" /> <-- note the extra "0"

imho its better to use textfield in the db, and store price data in the
'Money' type (off course, you must serialize this field in your model).

don't forget to install money.gem and `require` it.

--
wbr, sh0ckfile.
FileForum moders team
http://www.fforum.ru
Brian H. (Guest)
on 2007-04-19 16:52
(Received via mailing list)
That's a good approach.

When I first started using Rails, I found this problem and it bugged me
so I
tried to write a plugin to override this behavior. I got it working but
it
was way more trouble than it was worth.

My approach was to add two new methods to my model.

#f retreives the wholesale price and formats it as a decimal
def format_wholesale_price
   sprintf("%01.2f", self.wholesale_price
end


# Sets the value (needed to make the form helper work
def format_wholesale_price=(value)
   self.wholesale_price = value
end


Then just use those in your helpers.

<%= form.text_field :format_wholesale_price %>


That should work.
This topic is locked and can not be replied to.