Formtastic number field with decimal precision?

梦想的初衷 提交于 2019-12-05 11:37:57

Try this:

%td= bought.input :sales_price, input_html: { class: 'span2', value: number_with_precision(bought.sales_price, precision: 2) }, label: false

Sales_price is being stored in your database with two decimal places, but you have to tell rails to format it that way when displaying the value.

Modify StringInput

@xnm's answer was helpful to me, but doing this on each input would be tedious, so I took it a step further to solve this problem application-wide.

I did this by modifying the behavior of regular input fields, which Formtastic calls StringInput, by creating my own version, as shown in in the Formtastic README.

The code below is for for DataMapper models, so that anytime a property is declared as Decimal, the input will show the correct number of decimal places. This approach could be modified for other ORMs.

# app/inputs/string_input.rb

# Modified version of normal Formtastic form inputs.
# When creating an input field for a DataMapper model property, see if it is
# of type Decimal. If so, display the value with the number of decimals
# specified on the model.
class StringInput < Formtastic::Inputs::StringInput
  def to_html
    dm_property = @object.class.properties.detect do |property| 
      property.name == @method
    end rescue nil

    if dm_property && dm_property.class == DataMapper::Property::Decimal
      @options[:input_html] ||= {}
      @options[:input_html][:value] ||= @template.number_with_precision(

        # What DataMapper calls "scale" (number of digits right of the decimal),
        # this helper calls "precision"
        @object.send(@method), precision: dm_property.options[:scale]
      )
    end

    super
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!