具有小数精度的Formtastic数字字段?

当然我错过了一些非常明显的东西……我有一个十进制精度为2的字段,但Formtastic只显示一个小数,除非实际值有2个位置。 我错过了什么?

模型:

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 

视图

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

注意到下面的回答,其他人在以后发现这个问题可能并不清楚:

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

试试这个:

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

Sales_price存储在数据库中,带有两个小数位,但是在显示值时必须告诉rails以这种方式格式化它。

修改StringInput

@ xnm的回答对我很有帮助,但是对每个输入执行此操作都会很乏味,所以我在应用程序范围内更进一步解决了这个问题。

我这样做是通过修改Formtastic调用StringInput的常规输入字段的行为,通过创建我自己的版本,如Formtastic README中所示 。

下面的代码适用于DataMapper模型,因此只要属性声明为Decimal ,输入就会显示正确的小数位数。 可以针对其他ORM修改此方法。

 # 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