Formtastic number field with decimal precision?

人盡茶涼 提交于 2019-12-07 05:00:55

问题


Surely I'm missing something pretty obvious... I have a field that is decimal with precision 2, but Formtastic is displaying it with only a single decimal, unless the actual value has 2 places. What am I missing?

Model:

create_table "items", :force => true do |t|
    t.string   "item_number"
    t.integer  "buyer_id"
    t.integer  "seller_id"
    t.string   "description"
    t.decimal  "sales_price", :precision => 10, :scale => 2, :default => 0.0
    t.datetime "created_at"
    t.datetime "updated_at"
end

View

%td= bought.input :sales_price, input_html: { class: 'span2'}, label: false

Noting answer from below, which might not be clear to others finding this later:

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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/8857770/formtastic-number-field-with-decimal-precision

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