0

我已经这样做了,没有任何问题,但今天我无法让它工作。

我有如下迁移

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

但是当我设置 BigDecimal 值时,小数部分会被忽略。通过查看Invoice里面的模型,rails console我可以看到它声明:amount 为 a 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

我在这里做错了什么?

4

1 回答 1

1

如此处所述(链接),您应该使用: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
于 2013-10-09T09:39:55.693 回答