简体   繁体   中英

Rails 2.3: how to get ActiveRecord errors types?

I'm on 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?

在此处输入图像描述

In rails 6, no monkeypatching needed:

c.errors.details.values.flatten.map{|h| h[:error] }

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM