如何格式化 Rails 编辑字段中显示的值? [英] How can I format the value shown in a Rails edit field?
问题描述
我想让编辑表单字段尽可能方便用户使用.例如,对于数值,我希望该字段以逗号显示(如 number_with_precision
).
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?
我正在使用 Rails FormBuilder.经过调查,我发现它使用 InstanceTag,它通过使用
获取字段的值,这意味着不会调用覆盖
.
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) %>
或者 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
但是你还是要使用:value
<%= f.text_field :my_attribute, :value => f.object.my_attribute %>
这看起来工作量很大.
这篇关于如何格式化 Rails 编辑字段中显示的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!