如何格式化Rails编辑字段中显示的值? [英] How can I format the value shown in a Rails edit field?
问题描述
我想尽可能方便用户编辑表单字段。例如,对于数值,我希望字段以逗号显示(如 number_with_precision
)。
这在显示器上很容易,但编辑怎么样?有没有一种好的方法来做到这一点?
我正在使用Rails FormBuilder。经过调查,我发现它使用InstanceTag,它通过使用< attribute> _value_before_type_cast
来取得字段的值,这意味着覆盖< attribute>
不会被调用。
迄今为止我所得到的最好的东西就是这样的:
<%= f.text_field:my_attribute,:value => number_with_precision(f.object.my_attribute)%>
或 my_attribute
可以返回格式化的值,像这样:
$ pre $ def $ my $ $ $ b $ ApplicationController.helpers.number_with_precision(read_attribute(:my_attribute))
end
但是您仍然必须使用:value
<%= f.text_field:my_attribute,:value => f.object.my_attribute%>
这似乎有很多工作要做。
I would like to make editing form fields as user-friendly as possible. For example, for numeric values, I would like the field to be displayed with commas (like number_with_precision
).
This is easy enough on the display side, but what about editing? Is there a good way to do this?
I am using the Rails FormBuilder. Upon investigation, I found that it uses InstanceTag, which gets the values for fields by using <attribute>_value_before_type_cast
which means overriding <attribute>
won't get called.
The best I have come up with so far is something like this:
<%= f.text_field :my_attribute, :value => number_with_precision(f.object.my_attribute) %>
Or my_attribute
could return the formatted value, like this:
def my_attribute
ApplicationController.helpers.number_with_precision(read_attribute(:my_attribute))
end
But you still have to use :value
<%= f.text_field :my_attribute, :value => f.object.my_attribute %>
This seems like a lot of work.
这篇关于如何格式化Rails编辑字段中显示的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!