Undefined method `to_d' for 0:Fixnum when trying to seed database?-Collection of common programming errors
When I’m trying to seed my database, I started getting this error:
rake aborted!
undefined method `to_d' for 0:Fixnum
This started after I added this method that strips my decimal columns of commas if their present (2,000.00 < 2000.00):
def cost=(num)
num.gsub!(',','') if num.is_a?(String)
self[:cost] = num.to_d
end
I have this same method for each of the columns of my Product
model:
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
Now looking at the trace (at https://gist.github.com/2265580) I think the problem may be my default_to_zero_if_necessary
method:
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
Maybe I can’t use my default_to_zero_if_necessary
method like this anymore? What’s really going on here? I’m not entirely sure.