Big Decimal Stored as 60.00, Returns as 0.0?
Asked Answered
S

1

7

I am customizing a Spree 2.3 application in Rails 4. When I save a price.amount, it appears to save correctly in the database, but when I retrieve it, it is wrapped in the BigDecimal class and returns 0.

How can I store, or retrieve, the correct value?

# in the form
<%= number_field_tag :amount %>

# controller action
@variant.price = params[:amount]

# appears in PostgresQL database as type 'numeric'
id: 35, amount: 60.00

# retrieved in Rails console as BigDecimal class instance
# looks like the wrong amount
2.1.1 :001 > Spree::Price.find_by_id(35).amount
=> #<BigDecimal:105806d20,'0.0',9(27)>

# converts to 0.0
2.1.1 :002 > Spree::Price.find_by_id(35).amount.to_f
=> 0.0

# testing data retrieval in the console
2.1.1 :003 > ActiveRecord::Base.connection.execute("SELECT * FROM spree_prices WHERE id=35").first
=> {"id"=>"35", "variant_id"=>"35", "amount"=>"60.00", "currency"=>"USD", "deleted_at"=>nil} 
2.1.1 :004 > Spree::Price.find(35)
=>  #<Spree::Price id: 35, variant_id: 35, amount: #<BigDecimal:109ec4a28,'0.0',9(27)>, currency: "USD", deleted_at: nil>
Servomechanism answered 30/7, 2014 at 23:28 Comment(6)
Almost looks like you're retrieving a different record than the one you saved.Vitriolic
Doesn't it? It's the correct record, though. I'll clarify that in the example.Servomechanism
In all realities that I have known, this should not be possible.Outhe
I'm not getting this behavior with spree 2.2.2 and rails 4.0.5Fortier
What is the column type?Osmose
@Michael: 'numeric' as noted in the question.Servomechanism
S
0

The problem was in a typo in the price model decorator. The pure PostgresQL doesn't trigger the callback, but using the 'find' method does. This accounts for the seemingly impossible results above.

#original price_decorator.rb
after_initialize :set_defaults

def set_defaults
  self.amount = 0.0
end

#corrected price_decorator.rb
after_initialize :set_defaults

def set_defaults
  self.amount ||= 0.0
end
Servomechanism answered 31/7, 2014 at 14:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.