我已经这样做了,没有任何问题,但今天我无法让它工作。
我有如下迁移
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
我在这里做错了什么?