[英]Rails 2.3: how to get ActiveRecord errors types?
我在 Rails 2.3.8 上; 我有這個模型:
class Coupon < ActiveRecord::Base
validate :foo
def foo
errors.add_to_base :foo_error
end
end
我的目的是檢索錯誤的類型,例如:
c = Coupon.new
c.valid?
c.errors.types #=> [[:base, :foo_error]]
我設法檢索了錯誤類型,但使用了一個非常奇怪的猴子補丁:
# 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]]
您知道檢索錯誤類型的更好方法嗎?
嘗試這個:
module ActiveRecord
class Errors
def types
@errors.values.flatten.map(&:type).uniq
end
end
end
如果您想避免猴子修補,您可以直接在 AR 對象上進行調用。
user.errors.instance_variable_get(:@errors).values.flatten.map(&:type).uniq
或者,您可以執行以下操作:
[].tap {|types| user.errors.each_error{|a,e| types << e.type}}.uniq
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.