Formating Float ActiveRecord attributes in text inputs

I have AMOUNT field that ActiveRecord maps to Float.
Then I use text_field helper to generate text inputs on forms.
Helper takes model object and attribute name and does not provide any
formatting abilities, thus 2.40 is shown as 2.4 which is fine with
floats but does not look good with currency.

I have worked around this issue by adding amount_f attribute to the
model that returns formatted string.
I do not like this “solution” for two reasons:

  1. formatting does not belong to models
  2. for every Float attribute I am forced to create another read/write
    attribute with identical logic.
    So this does not look right. What else?

I have tried to override #to_s on Float attribute but Float is a
singleton and overriding is not allowed.
I have tried to inherit from Float and override it there but did not get
it to work either.

Can someone post an elegant and clean solution for this problem?

Sergei S. wrote:

I have AMOUNT field that ActiveRecord maps to Float.
Then I use text_field helper to generate text inputs on forms.
Helper takes model object and attribute name and does not provide any
formatting abilities, thus 2.40 is shown as 2.4 which is fine with
floats but does not look good with currency.

Change the line

options[“value”] ||= value_before_type_cast unless field_type == “file”

in actionpack/lib/action_view/helpers/form_helper.rb to

unless field_type == “file”
options[“value”] ||= options[“format”] ? format(options[“format”],
value) : value_before_type_cast
end

Then you can either write:

<%= text_field :product, price, :format => ‘%.2f’ %>

or you can write a helper:

def usd_field(object_name, method, options = {})
text_field(object_name, method, options.merge(:format => ‘%.2f’))
end


We develop, watch us RoR, in numbers too big to ignore.

Thank you Mark,

Your helper source code quote made me realize that I can pass ‘value’
attribute from outside, so solution is simple:

If I want to see formatted rate I
<%= text_field :detail, :rate, :value =>
number_to_justcurrency(@detail.rate) %>

And that is it! Nice. Go Rais Go!

Sergei S.
Red Leaf Software LLC http://www.redleafsoft.com

Sergei S. wrote:

Your helper source code quote made me realize that I can pass ‘value’
attribute from outside, so solution is simple:

If I want to see formatted rate I
<%= text_field :detail, :rate, :value =>
number_to_justcurrency(@detail.rate) %>

That’s a good idea to avoid patching Rails by setting the value
explicitly. You can make it general by mimicking core code:

def usd_field(object, method, options = {})
amount = ‘%.2f’ % instance_variable_get("@#{object}").send(method)
text_field object, method, options.merge(:value => amount)
end


We develop, watch us RoR, in numbers too big to ignore.