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

后端 未结 6 1970
别跟我提以往
别跟我提以往 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:28

    You can use the number_format plugin. By specifying a number_format for an existing numeric attribute inside your model, the attribute will now appear as formatted to Rails in all forms and views. It will also be parsed back from that format (when assigned via forms) prior to insertion into the database. (The plugin also creates purely numeric unformatted_ accessors which can continue to be used for arithmetic, or for direct numerical assignment or retrieval by you for seamless integration.)

    class MyModel < ActiveRecord::Base
      # this model has the balance attribute, which we
      #  want to display using formatting in views,
      #  although it is stored as a numeric in the database
      number_format :balance, 
                    :precision => 2,
                    :delimiter => ',',
                    :strip_trailing_zeros => false
    
      def increment_balance
        unformatted_balance += 10
      end
    

    You can also combine the above with a Javascript solution, which can force the user to maintain the decimal point and thousands separators in place while editing, although this is really not necessary.

提交回复
热议问题