ruby-on-rails – 大十进制存储为60.00,返回0.0?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 大十进制存储为60.00,返回0.0?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Rails 4中定制Spree 2.3应用程序.当我保存price.amount时,它似乎在数据库中正确保存,但是当我检索它时,它被包装在BigDecimal类中并返回0.

如何存储或检索正确的值?

# 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,9(27)>,currency: "USD",deleted_at: nil>

解决方法

问题出在价格模型装饰器的拼写错误中.纯Postgresql不会触发回调,但使用’find’方法会.这解释了上面看似不可能的结果.
#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
原文链接:https://www.f2er.com/ruby/268033.html

猜你在找的Ruby相关文章