[英]Rails 2.3: how to get ActiveRecord errors types?
I'm on Rails 2.3.8;我在 Rails 2.3.8 上; I have this model:
我有这个模型:
class Coupon < ActiveRecord::Base
validate :foo
def foo
errors.add_to_base :foo_error
end
end
My purpose is to retrieve the types of the errors, for example something like this:我的目的是检索错误的类型,例如:
c = Coupon.new
c.valid?
c.errors.types #=> [[:base, :foo_error]]
I managed to retrieve the error types, but with a really weird monkeypatch:我设法检索了错误类型,但使用了一个非常奇怪的猴子补丁:
# in config/initializers/active_record_errors_types.rb
module ActiveRecord
class Errors
def types
instance_variable_get(:@errors).map do |k,v|
[ k.to_sym, v[0].instance_variable_get(:@type) ]
end
end
end
end
c = Coupon.new
c.valid?
c.errors.types #=> [[:base, :foo_error]]
Do you know a better way to retrieve error types?您知道检索错误类型的更好方法吗?
Try this:尝试这个:
module ActiveRecord
class Errors
def types
@errors.values.flatten.map(&:type).uniq
end
end
end
If you want to avoid the monkey patching you can directly make the call on the AR object.如果您想避免猴子修补,您可以直接在 AR 对象上进行调用。
user.errors.instance_variable_get(:@errors).values.flatten.map(&:type).uniq
Alternatively you can do the following:或者,您可以执行以下操作:
[].tap {|types| user.errors.each_error{|a,e| types << e.type}}.uniq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.