Zyr*_*ren 16 activerecord ruby-on-rails
使用save!保存模型时,我遇到验证错误的问题.ActiveRecord错误模型错误消息是空白的,所以我不知道在验证尝试中发生了什么错误.当我根据文档尝试errors.full_messages或errors.each_full时,它应该显示错误,而不是错误.
我试图保存的模型是Orders模型(使用Spree的电子商务网站).当订单中的商品被删除时,update_totals!被调用,重新计算总数,然后保存!被调用,它会触发验证错误(这个错误很少发生,但只有当我登录时,我才能找到它的原因).订单模型在其模型中有两个验证:
validates_numericality_of :item_total
validates_numericality_of :total
Run Code Online (Sandbox Code Playgroud)
我记录了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[]
Run Code Online (Sandbox Code Playgroud)
item_total和total以十进制(8,2)存储在mySQL数据库中.最后一行是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
Run Code Online (Sandbox Code Playgroud)
我想我的问题是双重的:
1.为什么我的activerecord错误模型没有说出验证错误是什么?
2.我该如何解决这个问题?我的item_total和total是否有效保存为十进制(8,2)?
我使用的是rails 2.3.5和spree 0.10.2
Vik*_*ary 27
如果您有before_validation声明并且如果它们返回,false那么您将收到一条Validation failed (ActiveRecord::RecordInvalid)带有空错误消息的消息(如果没有其他错误).
请注意,before_validation回调不能返回false(nil可以)并且这可能偶然发生,例如,如果您false在该回调方法中的最后一行中分配布尔属性.明确地写入return true你的回调方法来使这个工作(或者true如果你的回调是一个块就在最后(正如Jesse Wolgamott在评论中所指出的)).
更新:这将不再是启动Rails 5.0的问题,因为return false将不再停止回调链(throw :abort现在将暂停回调链).
更新:ActiveRecord::RecordNotSaved: Failed to save the record如果回调返回,您可能还会收到false.