How can I format the value shown in a Rails edit field?

后端 未结 6 1963
别跟我提以往
别跟我提以往 2020-12-01 07:56

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

6条回答
  •  既然无缘
    2020-12-01 08:16

    I prefer your first answer, with the formatting being done in the view. However, if you want to perform the formatting in the model, you can use wrapper methods for the getter and setter, and avoid having to use the :value option entirely.

    You'd end up with something like this.

    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 %>
    

    Railscasts covered this with a Time object in a text_field in episode #32. The really clever part of this is how they handle validation errors. It's worth watching the episode for that alone.

提交回复
热议问题