【问题标题】:Formtastic number field with decimal precision?具有小数精度的格式数字字段?
【发布时间】:2012-01-13 21:56:20
【问题描述】:

我肯定遗漏了一些非常明显的东西...我有一个精度为 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

【问题讨论】:

    标签: ruby-on-rails formtastic


    【解决方案1】:

    试试这个:

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

    Sales_price 以两位小数存储在您的数据库中,但您必须告诉 rails 在显示值时以这种方式对其进行格式化。

    【讨论】:

    • 非常感谢。我忘了提到bought 是一个嵌套属性。在尝试您的解决方案时,我收到一个错误,指出 sales_price 是一个未定义的方法。我需要以不同的方式引用它吗?
    • 啊,找到答案了……和上面一样,但是加了'object':value: number_with_precision(bought.object.sales_price,precision: 2)
    【解决方案2】:

    修改字符串输入

    @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
    

    【讨论】:

    • 一个非常好的解决方案。我必须在下一个项目中尝试一下。
    猜你喜欢
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    相关资源
    最近更新 更多