Custom formatting of float within form_for
Is there any way to control the float format in a form field?
I want to format a float like an integer if the modulus is 0, otherwise display the float as is. I overrode the Model accessor to do this formatting.
When an edit form is loaded, I would like to have the following开发者_如何学Go transformations:
stored value | accessor returns | form field shows
---------------------------------------------------
1.0 | 1 | 1
1.5 | 1.5 | 1.5
However, form_for appears to be accessing the attribute directly, thereby displaying the float as is.
Any ideas on how to get around this? Thanks.
Using
def my_float
raw = read_attribute(:my_float)
if raw == raw.to_i
raw.to_i
else
raw
end
end
within form_for
will not work as noted before. Tried multiple times. IMHO it is one of more severe design issues with rails. In general you don't have straight forward (restful) access to model from your view.
You could override the attribute reader, something like this:
def myfloat
if @myfloat == @myfloat.to_i
@myfloat.to_i
else
@myfloat
end
end
Now the returned value are correctly formatted for your form and still usable in your application.
I do believe it will work when you do something like this:
<%= f.text_field :field_attribute, :value => format_method(f.object.field_attribute) %>
format_method is whatever method you use within the model to override the formatting when accessing it that way.
Veger's solution will work if you use read_attribute
to get the "raw" value:
def myfloat
raw = read_attribute(:myfloat)
if raw == raw.to_i
raw.to_i
else
raw
end
end
As always when comparing floats to integers, you'd want to be careful about rounding.
You can override respond_to? in the Model to stop value_before_type_cast from being called.
def respond_to?(*args)
if args.first.to_s == "my_float_before_type_cast"
false
else
super
end
end
And then you need also:
def my_float
raw = read_attribute(:my_float)
if raw == raw.to_i
raw.to_i
else
raw
end
end
精彩评论