开发者

Can't get decimals to display in text field for Rails 3

Confused Rails 3 newbie. My model has a purchase_price attribute defined like this:

t.decimal :purchase_price, :precision => 12, :scale => 2, :default => 0.00

My goal is to have a simple Rails 3 app where I can view and edit this value. In my model, I defined a custom getter to force 2 decimal places to always exist.

def purchase_price
  sprintf( "%.2f",attributes['purchase_price'])
end

This works correctly from the console and when I display the show page. On the edit page I have a text field to edit this value. My problem is that if this value is saved as '123.00' the value is displayed as '123.0'.

开发者_开发百科

Questions:

  1. Why is my custom getter not getting called?
  2. Why is this displayed with 1 decimal and not 2 decimals?

Update

  1. Decimal value as stored in MySQL: 100.20
  2. Value returned from console: 100.20
  3. Value displayed in text field: 100.2
  4. Value returned via Firebug: "100.2"
  5. The text field length is not an issue.
  6. If the value in the db is 100.21, it is displayed correctly as 100.21


Try this

f.text_field :purchase_price, :value=>number_to_currency(f.object.purchase_price, :unit=>'')

That should convert the number to a currency (with two decimal places) and the :unit=>'' will exclude the "$".

And I'd recommend removing your custom purchase_price method and using the number_to_currency helper where needed instead. Overriding the purchase_price accessor isn't a bad idea but it could confuse some things that might be expecting a number rather than a string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜