如何格式化Rails编辑字段中显示的值?

Luk*_*ncl 31 ruby forms ruby-on-rails

我想让编辑表单字段尽可能方便用户使用.例如,对于数值,我希望用逗号(例如number_with_precision)显示该字段.

这在显示器方面很容易,但是编辑呢?有没有办法做到这一点?

我正在使用Rails FormBuilder.经过调查,我发现它使用InstanceTag,它通过使用获取字段的值,<attribute>_value_before_type_cast这意味着<attribute>不会调用覆盖.

Luk*_*ncl 38

到目前为止我提出的最好的是这样的:

<%= f.text_field :my_attribute, :value => number_with_precision(f.object.my_attribute) %>
Run Code Online (Sandbox Code Playgroud)

或者my_attribute可以返回格式化的值,如下所示:

def my_attribute
  ApplicationController.helpers.number_with_precision(read_attribute(:my_attribute))
end
Run Code Online (Sandbox Code Playgroud)

但你还是要用 :value

<%= f.text_field :my_attribute, :value => f.object.my_attribute %>
Run Code Online (Sandbox Code Playgroud)

这似乎很多工作.


jdl*_*jdl 9

我更喜欢你的第一个答案,格式化在视图中完成.但是,如果要在模型中执行格式化,可以对getter和setter使用包装器方法,并避免完全使用:value选项.

你最终会得到这样的东西.

def my_attribute_string
  foo_formatter(myattribute)
end

def my_attribute_string=(s)
  # Parse "s" or do whatever you need to with it, then set your real attribute.
end

<%= f.text_field :my_attribute_string %>
Run Code Online (Sandbox Code Playgroud)

Railscasts在第32集的text_field中用Time对象覆盖了它.其中非常聪明的部分是它们如何处理验证错误.仅凭这一点值得观看这一集.


Jos*_*ris 5

这是一个老问题,但如果有人遇到这个问题,您可以使用 number_to_X 助手。它们具有显示编辑值时可能需要的所有属性:

<%= f.text_field :my_number, :value => number_to_human(f.object.my_number, :separator => '', :unit => '', :delimiter => '', :precision => 0) %>
Run Code Online (Sandbox Code Playgroud)

还有更多可用的属性:http : //api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html