Ruby-on-rails 在 Rails 中,除了验证错误之外,如何找出导致 .save() 失败的原因?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4714001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In rails, how can I find out what caused a .save() to fail, other than validation errors?
提问by kdt
I have an ActiveRecord model which is returning truefrom valid?(and .errors is empty), but is returning falsefrom save(). If the model instance is valid, how can I find out what's causing the save to fail?
我有它返回一个ActiveRecord模型true从valid?(和.errors是空的),但返回false的save()。如果模型实例有效,我如何找出导致保存失败的原因?
采纳答案by Andrew
Check all your callbacks.
检查所有回调。
I had a problem like this where I had and "after_validate" method that was failing after I had made a bunch of changes to the model. The model was valid but the "after_validate" was returning false, so if I used model.validit said true, but then if I saved it gave me validation errors (passed through from the after_validate callback). It was weird.
我有一个这样的问题,我有一个“after_validate”方法,在我对模型进行了一系列更改后失败了。该模型有效但“after_validate”返回false,所以如果我使用model.valid它说true,但是如果我保存它会给我验证错误(从after_validate回调传递)。这很奇怪。
Look at the application trace and you should be able to see what line of code is raising the exception.
查看应用程序跟踪,您应该能够看到哪行代码引发了异常。
回答by Andy Lindeman
Try using the bang version save!(with an exclamation mark at the end) and inspecting the resulting error.
尝试使用 bang 版本save!(末尾带有感叹号)并检查由此产生的错误。
回答by Sam Alex
If @user.save(for example) returns false, then just run this to get all the errors:
如果@user.save(例如)返回false,则只需运行它以获取所有错误:
@user.errors.full_messages
回答by Pencilcheck
Yea, I fixed this issue by making sure I return true in all my before_* callbacks then it starts working :)
是的,我通过确保我在所有 before_* 回调中返回 true 然后它开始工作来解决这个问题:)
回答by Ian Vaughan
The problem I had was that I had forgotten to add the validation to the model.
我遇到的问题是我忘记将验证添加到模型中。
class ContactGroup < ActiveRecord::Base
validates_presence_of :name
end

