更好的方式来访问个人Rails的ActiveRecord的错误? [英] Better way to access individual Rails ActiveRecord error?
本文介绍了更好的方式来访问个人Rails的ActiveRecord的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图访问一个ActiveRecord ::错误对象的类型属性。我这样做的原因是因为我想将用户重定向到视验证失败的类型不同的页面(属性可以通过多种方式验证失败,那么该属性本身是不够的)。
I'm trying to access the type attribute of an ActiveRecord::Error object. The reason I'm doing this is because I want to redirect a user to a different page depending on the type of validation that failed (an attribute can fail validation in several ways, so the attribute itself is insufficient).
我发现,我能做到这一点的唯一方法是:
The only way I've found that I can do this is:
obj.errors.instance_variable_get(:@错误)[ATTR] [0] .TYPE
这只是普通的讨厌。有没有更好的办法?
which is just plain nasty. Is there a better way?
推荐答案
看起来像你最好的选择是延长的ActiveRecord ::错误
。
Looks like your best bet is to extend ActiveRecord::Errors
.
class ActiveRecord::Errors
def error_type(attr)
@errors[attr] && @errors[attr].first.type
end
end
这篇关于更好的方式来访问个人Rails的ActiveRecord的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文