0
當我試圖種子我的數據庫,我開始收到此錯誤:嘗試種子數據庫時未定義方法'to_d'for 0:Fixnum?
rake aborted!
undefined method `to_d' for 0:Fixnum
這開始後,我加入這個方法去掉逗號我小數列,如果他們的存在(2,000.00 < 2000.00):
def cost=(num)
num.gsub!(',','') if num.is_a?(String)
self[:cost] = num.to_d
end
我有這同樣的方法對我的每個Product
模型列:
create_table :products do |t|
t.decimal :cost, :precision => 11, :scale => 2
t.decimal :tax_rate, :precision => 8, :scale => 2
t.decimal :shipping_cost, :precision => 8, :scale => 2
t.decimal :cost_per_unit, :precision => 11, :scale => 2
t.decimal :unit_amount, :precision => 16
現在看跟蹤(在https://gist.github.com/2265580)我認爲這個問題可能是我default_to_zero_if_necessary
方法:
Product.rb
before_validation :default_to_zero_if_necessary, :on => :create
private
def default_to_zero_if_necessary
self.tax_rate = 0 if self.tax_rate.blank?
self.shipping_cost = 0 if self.shipping_cost.blank?
self.cost = 0 if self.cost.blank?
self.cost_per_unit = 0 if self.cost_per_unit.blank?
self.unit_amount = 0 if self.unit_amount.blank?
end
也許我不能用我的default_to_zero_if_necessary
方法是這樣了嗎?這裏究竟發生了什麼?我不完全確定。
哇,就這麼簡單。這個伎倆,謝謝。 – LearningRoR 2012-03-31 16:43:02