跳到內容 跳到搜尋

Active Model Error

表示單一錯誤

方法
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

所有參數都必須與錯誤的屬性值相等,才

# 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