【问题标题】:Big Decimal Stored as 60.00, Returns as 0.0?大十进制存储为 60.00,返回为 0.0?
【发布时间】:2014-09-22 19:00:00
【问题描述】:

我正在 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,'0.0',9(27)>, currency: "USD", deleted_at: nil>

【问题讨论】:

  • 看起来您检索的记录与您保存的记录不同。
  • 不是吗?不过,这是正确的记录。我将在示例中阐明这一点。
  • 在我所知道的所有现实中,这是不可能的。
  • 我在 spree 2.2.2 和 rails 4.0.5 中没有这种行为
  • 什么是列类型?

标签: ruby-on-rails ruby-on-rails-4 postgresql-9.1 spree ruby-2.0


【解决方案1】:

问题在于价格模型装饰器中的拼写错误。纯 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

【讨论】:

    猜你喜欢
    • 2018-02-22
    • 2021-08-31
    • 2021-04-01
    • 2020-03-28
    • 2020-11-23
    • 2017-01-13
    • 2016-07-31
    • 1970-01-01
    • 2013-06-05
    相关资源
    最近更新 更多