Rails 3 AR表示十进制字段为整数

时间:2013-10-09 09:08:01

标签: ruby-on-rails ruby-on-rails-3 activerecord

我已经完成了这个,没有任何问题, 但是今天我无法让它发挥作用。

我的迁移如下

class AddAmountToInvoices < ActiveRecord::Migration
  def change
    add_column :invoices, :amount, :decimal, :precision => 2
  end
end

但是当我设置BigDecimal值时,小数部分会忽略小数部分。 通过查看Invoice中的rails console模型,我可以看到它将:amount声明为integer,如您所见:

 => Invoice(id: integer, invoice_number: integer, brogliaccio_id: string, kind: string, tax_id: string, payment_method: string, openmanager_user_id: string, created_at: datetime, updated_at: datetime, event_id: integer, amount: integer)

这是invoice.rb模型:

# encoding: utf-8
class Invoice < ActiveRecord::Base
  belongs_to :event

  KINDS = ["Detrazione", "Non Detrazione"]
  TAX_IDS = {"4%" => "004", "10%" => "010", "22%" => "022"}
  PAYMENT_METHODS = {"Bonifico" => "BB", "Contanti" => "CO", "Finanziamento" => "FI", "Assegno" => "AS"}

  attr_accessor :amount_string # we need this to handle custom number-format

  attr_accessible :amount_string, :brogliaccio_id, :invoice_number, :kind, :openmanager_user_id, :payment_method, :tax_id, :amount

  validates_presence_of :amount, :kind, :payment_method, :tax_id, :openmanager_user_id
  validates_inclusion_of :kind, :in => Invoice::KINDS
  validates_inclusion_of :tax_id, :in => Invoice::TAX_IDS.values()
  validates_inclusion_of :payment_method, :in => Invoice::PAYMENT_METHODS.values()
  validate :minimum_amount

  # we get a string formatted as "10.000,50" that needs to be converted to "10000.50"
  # to assure it will be correctly interpretated
  def amount_string=(value)
    value = value.gsub(/\./, '').gsub(/,/, '.')
    self.amount = BigDecimal.new(value, 2)
  end

  def amount_string
    self.amount
  end

  private
  def minimum_amount
    unless self.amount.blank?
      if self.amount < BigDecimal.new("10.0")
        errors.add(:base, "min invoice amount must be 10$")
      end
    end
  end

end

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

如此处所述(link),您应该使用:scale代替:precision(或两者)。精度是相关数字的数量,因此如果将其设置为2,则有2个相关数字,如10或12或1.2或0.3,依此类推。

  

“为了清楚起见:精度是有效位数,而刻度是小数点后可以存储的位数。例如,数字123.45的精度为5,刻度为2精度为5,刻度为2的小数范围为-999.99到999.99。“

所以如果你想要一个两位数的金额。迁移应如下所示:

class AddAmountToInvoices < ActiveRecord::Migration
    def change
        add_column :invoices, :amount, :decimal, :scale => 2
    end
end