跳至内容 跳至搜索

Active Model 错误

表示单个错误

方法
A
D
F
M
N
S

常量

CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict]
 
MESSAGE_OPTIONS = [:message]
 

属性

[R] attribute

base 的属性,该错误属于该属性

[R] base

该错误所属的对象

[R] options

调用 errors#add 时提供的选项

[R] raw_type

调用 errors#add 时作为第二个参数提供的原始值

[R] type

错误类型,默认值为 :invalid,除非指定

类公共方法

new(base, attribute, type = :invalid, **options)

# File activemodel/lib/active_model/error.rb, line 103
def initialize(base, attribute, type = :invalid, **options)
  @base = base
  @attribute = attribute
  @raw_type = type
  @type = type || :invalid
  @options = options
end

实例公共方法

detail()

别名:details

details()

返回错误详细信息。

error = ActiveModel::Error.new(person, :name, :too_short, count: 5)
error.details
# => { error: :too_short, count: 5 }
也称为:detail
# File activemodel/lib/active_model/error.rb, line 149
def details
  { error: raw_type }.merge(options.except(*CALLBACKS_OPTIONS + MESSAGE_OPTIONS))
end

full_message()

返回完整的错误消息。

error = ActiveModel::Error.new(person, :name, :too_short, count: 5)
error.full_message
# => "Name is too short (minimum is 5 characters)"
# File activemodel/lib/active_model/error.rb, line 159
def full_message
  self.class.full_message(attribute, message, @base)
end

match?(attribute, type = nil, **options)

查看错误是否与提供的 attributetypeoptions 匹配。

省略的参数不会被检查匹配。

# File activemodel/lib/active_model/error.rb, line 166
def match?(attribute, type = nil, **options)
  if @attribute != attribute || (type && @type != type)
    return false
  end

  options.each do |key, value|
    if @options[key] != value
      return false
    end
  end

  true
end

message()

返回错误消息。

error = ActiveModel::Error.new(person, :name, :too_short, count: 5)
error.message
# => "is too short (minimum is 5 characters)"
# File activemodel/lib/active_model/error.rb, line 135
def message
  case raw_type
  when Symbol
    self.class.generate_message(attribute, raw_type, @base, options.except(*CALLBACKS_OPTIONS))
  else
    raw_type
  end
end

strict_match?(attribute, type, **options)

查看错误是否与提供的 attributetypeoptions 完全匹配。

所有参数必须与 Error 的自身属性相等,才能被视为严格匹配。

# File activemodel/lib/active_model/error.rb, line 184
def strict_match?(attribute, type, **options)
  return false unless match?(attribute, type)

  options == @options.except(*CALLBACKS_OPTIONS + MESSAGE_OPTIONS)
end

实例受保护方法

attributes_for_hash()

# File activemodel/lib/active_model/error.rb, line 204
def attributes_for_hash
  [@base, @attribute, @raw_type, @options.except(*CALLBACKS_OPTIONS)]
end