我在使用 save! 保存模型时遇到验证错误问题。 ActiveRecord 错误模型错误消息为空白,因此我不知道验证尝试中发生了什么错误。当我根据以下内容尝试errors.full_messages或errors.each_full时文档 http://ar.rubyonrails.org/classes/ActiveRecord/Errors.html,它应该显示错误,但事实并非如此。
我试图保存的模型是订单模型(使用 Spree 的电子商务网站)。当订单中的某个项目被删除时,update_totals!被调用重新计算总数,然后保存!被调用,这会触发验证错误(此错误很少发生,但仅在我登录时发生,我还没有找到原因)。订单模型在其模型中有两个验证:
validates_numericality_of :item_total
validates_numericality_of :total
我记录了 order.item_total.inspect、order.total.inspect 和 order.errors.full_messages.inspect 并得到了这个:
Wed Jan 25 08:53:08 -0800 2012order item total: #<BigDecimal:15780c60,'0.279E2',8(16)>
Wed Jan 25 08:53:08 -0800 2012order total: #<BigDecimal:152bf410,'0.2448225E2',12(20)>
Wed Jan 25 08:53:08 -0800 2012: ERRORS SAVING ORDER:
Wed Jan 25 08:53:08 -0800 2012[]
item_total 和total 在mySQL 数据库中存储为decimal(8,2)。最后一行是 order.errors.full_messages.inspect,它是一个空数组。验证错误如下所示:
ActiveRecord::RecordInvalid (Validation failed: {{errors}}):
vendor/extensions/mgx_core/app/models/order.rb:382:in `update_totals!'
vendor/extensions/mgx_core/app/controllers/line_items_controller.rb:7:in `destroy'
app/middleware/flash_session_cookie_middleware.rb:19:in `call'
C:\Users\mgx\My Documents\Aptana Studio 3 Workspace\catalogue-spree\script\server:3
c:/Ruby187/lib/ruby/gems/1.8/gems/ruby-debug-ide-0.4.16/lib/ruby-debug-ide.rb:112:in `debug_load'
c:/Ruby187/lib/ruby/gems/1.8/gems/ruby-debug-ide-0.4.16/lib/ruby-debug-ide.rb:112:in `debug_program'
c:/Ruby187/lib/ruby/gems/1.8/gems/ruby-debug-ide-0.4.16/bin/rdebug-ide:87
c:/Ruby187/bin/rdebug-ide:19:in `load'
c:/Ruby187/bin/rdebug-ide:19
我想我的问题是双重的:
1. 为什么我的 activerecord 错误模型没有说明验证错误是什么?
2. 如何解决这个问题?我的 item_total 和total 是否可以保存为decimal(8,2)?
我使用的是 Rails 2.3.5 和 spree 0.10.2