Active Model 錯誤
提供與錯誤相關的功能,可以納入您的物件中,用於處理錯誤訊息並與 Action View 說明器互動。
最小的實作可能是
class Person
# Required dependency for ActiveModel::Errors
extend ActiveModel::Naming
def initialize
@errors = ActiveModel::Errors.new(self)
end
attr_accessor :name
attr_reader :errors
def validate!
errors.add(:name, :blank, message: "cannot be nil") if name.nil?
end
# The following methods are needed to be minimally implemented
def read_attribute_for_validation(attr)
send(attr)
end
def self.human_attribute_name(attr, options = {})
attr
end
def self.lookup_ancestors
[self]
end
end
最後三個方法在您的物件中是必要的,才能使錯誤訊息正確產生並也能處理多種語言。當然,如果您將您的物件延伸至 ActiveModel::Translation
,則不必實作最後兩個。同樣地,使用 ActiveModel::Validations
則會為您處理與驗證相關的方法。
上述方法允許您執行下列操作
person = Person.new
person.validate! # => ["cannot be nil"]
person.errors.full_messages # => ["name cannot be nil"]
# etc..
- #
- A
- C
- D
- E
- F
- G
- H
- I
- K
- M
- N
- O
- S
- T
- W
屬性
[R] | errors | 錯誤物件的實際陣列 此方法別名為 objects。 |
[R] | objects | 錯誤物件的實際陣列 此方法別名為 objects。 |
類別公開方法
new(base) 連結
傳入使用錯誤物件的物件實例。
class Person
def initialize
@errors = ActiveModel::Errors.new(self)
end
end
實例公開方法
[](attribute) 連結
當傳入符號或方法名稱時,傳回方法的錯誤陣列。
person.errors[:name] # => ["cannot be nil"]
person.errors['name'] # => ["cannot be nil"]
add(attribute, type = :invalid, **options) 連結
在 attribute 上新增類型為 type 的新錯誤。可以將多個錯誤新增至相同的 attribute。若未提供 type,則假設為 :invalid。
person.errors.add(:name)
# Adds <#ActiveModel::Error attribute=name, type=invalid>
person.errors.add(:name, :not_implemented, message: "must be implemented")
# Adds <#ActiveModel::Error attribute=name, type=not_implemented,
options={:message=>"must be implemented"}>
person.errors.messages
# => {:name=>["is invalid", "must be implemented"]}
若 type 為字串,系統將其用作錯誤訊息。
若 type 為符號,系統將使用適當的範圍將其翻譯(請參閱 generate_message)。
person.errors.add(:name, :blank)
person.errors.messages
# => {:name=>["can't be blank"]}
person.errors.add(:name, :too_long, count: 25)
person.errors.messages
# => ["is too long (maximum is 25 characters)"]
若 type 為程序,系統將予以呼叫,允許在錯誤中使用類似 Time.now 之類的內容。
如果 :strict 選項設為 true,系統將引發 ActiveModel::StrictValidationFailed
錯誤,而不是新增錯誤。:strict 選項也可以設為任何其他例外。
person.errors.add(:name, :invalid, strict: true)
# => ActiveModel::StrictValidationFailed: Name is invalid
person.errors.add(:name, :invalid, strict: NameIsInvalid)
# => NameIsInvalid: Name is invalid
person.errors.messages # => {}
若錯誤未直接與單一屬性相關聯,attribute
應設為 :base
。
person.errors.add(:base, :name_or_email_blank,
message: "either name or email must be present")
person.errors.messages
# => {:base=>["either name or email must be present"]}
person.errors.details
# => {:base=>[{error: :name_or_email_blank}]}
# File activemodel/lib/active_model/errors.rb, line 342 def add(attribute, type = :invalid, **options) attribute, type, options = normalize_arguments(attribute, type, **options) error = Error.new(@base, attribute, type, **options) if exception = options[:strict] exception = ActiveModel::StrictValidationFailed if exception == true raise exception, error.full_message end @errors.append(error) error end
added?(屬性, 類型 = :invalid, 選項 = {}) 永久連結
如果錯誤符合提供的屬性
和類型
,就會回傳 true
,反之則回傳 false
。 類型
的處理方式與 add
相同。
person.errors.add :name, :blank
person.errors.added? :name, :blank # => true
person.errors.added? :name, "can't be blank" # => true
如果錯誤需要選項,則會在選項正確時回傳 true
,在選項不正確或遺漏時回傳 false
。
person.errors.add :name, :too_long, count: 25
person.errors.added? :name, :too_long, count: 25 # => true
person.errors.added? :name, "is too long (maximum is 25 characters)" # => true
person.errors.added? :name, :too_long, count: 24 # => false
person.errors.added? :name, :too_long # => false
person.errors.added? :name, "is too long" # => false
# File activemodel/lib/active_model/errors.rb, line 372 def added?(attribute, type = :invalid, options = {}) attribute, type, options = normalize_arguments(attribute, type, **options) if type.is_a? Symbol @errors.any? { |error| error.strict_match?(attribute, type, **options) } else messages_for(attribute).include?(type) end end
as_json(選項 = nil) 永久連結
會回傳可做為此物件的 JSON 表示形式的 Hash
。您可以傳遞 :full_messages
選項。這可決定 JSON 物件是否應包含完整訊息(預設為否)。
person.errors.as_json # => {:name=>["cannot be nil"]}
person.errors.as_json(full_messages: true) # => {:name=>["name cannot be nil"]}
attribute_names() 永久連結
回傳所有錯誤屬性名稱
person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
person.errors.attribute_names # => [:name]
clear 永久連結
清除所有錯誤。不過,清除錯誤不會讓模型有效。下次執行驗證時(例如,透過 ActiveRecord::Validations#valid?
),如果任何驗證失敗,錯誤集合將再次填滿。
資料來源: GitHub
# File activemodel/lib/active_model/errors.rb, line 80
delete(屬性, 類型 = nil, **選項) 永久連結
刪除 金鑰
的訊息。回傳已刪除的訊息。
person.errors[:name] # => ["cannot be nil"]
person.errors.delete(:name) # => ["cannot be nil"]
person.errors[:name] # => []
# File activemodel/lib/active_model/errors.rb, line 215 def delete(attribute, type = nil, **options) attribute, type, options = normalize_arguments(attribute, type, **options) matches = where(attribute, type, **options) matches.each do |error| @errors.delete(error) end matches.map(&:message).presence end
each(&區塊) 永久連結
迭代每個錯誤物件。
person.errors.add(:name, :too_short, count: 2)
person.errors.each do |error|
# Will yield <#ActiveModel::Error attribute=name, type=too_short,
options={:count=>3}>
end
資料來源: GitHub
# File activemodel/lib/active_model/errors.rb, line 67
full_message(屬性, 訊息) 永久連結
會回傳給定屬性的完整訊息。
person.errors.full_message(:name, 'is invalid') # => "Name is invalid"
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/errors.rb, line 451 def full_message(attribute, message) Error.full_message(attribute, message, @base) end
full_messages() 連結
傳回陣列中的所有完整錯誤訊息。
class Person
validates_presence_of :name, :address, :email
validates_length_of :name, in: 5..30
end
person = Person.create(address: '123 First St.')
person.errors.full_messages
# => ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Email can't be blank"]
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/errors.rb, line 415 def full_messages @errors.map(&:full_message) end
full_messages_for(attribute) 連結
傳回陣列中特定屬性的所有完整錯誤訊息。
class Person
validates_presence_of :name, :email
validates_length_of :name, in: 5..30
end
person = Person.create()
person.errors.full_messages_for(:name)
# => ["Name is too short (minimum is 5 characters)", "Name can't be blank"]
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/errors.rb, line 430 def full_messages_for(attribute) where(attribute).map(&:full_message).freeze end
generate_message(attribute, type = :invalid, options = {}) 連結
將錯誤訊息翻譯成其預設範圍 (activemodel.errors.messages
) 中。
Error
訊息會先在 activemodel.errors.models.MODEL.attributes.ATTRIBUTE.MESSAGE
中搜尋,若找不到,會在 activemodel.errors.models.MODEL.MESSAGE
中搜尋,若仍找不到,則傳回預設訊息的翻譯 (例如:activemodel.errors.messages.MESSAGE
)。經過翻譯的 model 名稱、屬性名稱和值可供插入。
在 model 中使用繼承時,它也會檢查所有繼承的 model,但僅在無法找到 model 本身時。例如:當您有 class Admin < User; end
,而您想要翻譯標題屬性的 :blank
錯誤訊息時,它會搜尋下列翻譯
-
activemodel.errors.models.admin.attributes.title.blank
-
activemodel.errors.models.admin.blank
-
activemodel.errors.models.user.attributes.title.blank
-
activemodel.errors.models.user.blank
-
您透過
options
hash 提供的任何預設值 (在activemodel.errors
範圍中) -
activemodel.errors.messages.blank
-
errors.attributes.title.blank
-
errors.messages.blank
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/errors.rb, line 479 def generate_message(attribute, type = :invalid, options = {}) Error.generate_message(attribute, type, @base, options) end
group_by_attribute() 連結
person.errors.group_by_attribute
# => {:name=>[<#ActiveModel::Error>, <#ActiveModel::Error>]}
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/errors.rb, line 289 def group_by_attribute @errors.group_by(&:attribute) end
import(error, override_options = {}) 連結
匯入一個錯誤。匯入的錯誤會包裝成 NestedError
,提供存取原始錯誤物件的功能。如果需要覆寫屬性或類型,請使用 override_options
。
選項
-
:attribute
- 覆寫錯誤所屬的屬性。 -
:type
- 覆寫錯誤的類型。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/errors.rb, line 154 def import(error, override_options = {}) [:attribute, :type].each do |key| if override_options.key?(key) override_options[key] = override_options[key].to_sym end end @errors.append(NestedError.new(@base, error, override_options)) end
include?(attribute) 連結
如果錯誤訊息包括特定鍵值 attribute
的錯誤,則傳回 true
;否則傳回 false
。
person.errors.messages # => {:name=>["cannot be nil"]}
person.errors.include?(:name) # => true
person.errors.include?(:age) # => false
merge!(other) 連結
合併來自 `other` 的錯誤,每個 Error
都以 NestedError
包裝。
參數
-
other
-ActiveModel::Errors
個體。
範例
person.errors.merge!(other)
messages_for(attribute) 連結
傳回給定屬性的所有錯誤訊息(以陣列格式)。
class Person
validates_presence_of :name, :email
validates_length_of :name, in: 5..30
end
person = Person.create()
person.errors.messages_for(:name)
# => ["is too short (minimum is 5 characters)", "can't be blank"]
of_kind?(attribute, type = :invalid) 連結
如果存在具有給定類型之屬性錯誤,則回傳 true,否則回傳 false。 類型
處理方式與 新增
類似。
person.errors.add :age
person.errors.add :name, :too_long, count: 25
person.errors.of_kind? :age # => true
person.errors.of_kind? :name # => false
person.errors.of_kind? :name, :too_long # => true
person.errors.of_kind? :name, "is too long (maximum is 25 characters)" # => true
person.errors.of_kind? :name, :not_too_long # => false
person.errors.of_kind? :name, "is too long" # => false
size 連結
傳回錯誤數目。
to_hash(full_messages = false) 連結
傳回 Hash
,其中包含屬性及其錯誤訊息。如果 full_messages
為 true,則它會包含完整訊息(參閱 full_message
)。
person.errors.to_hash # => {:name=>["cannot be nil"]}
person.errors.to_hash(true) # => {:name=>["name cannot be nil"]}
where(attribute, type = nil, **options) 連結
搜尋與 attribute
、type
或 options
符合的錯誤。
只會比對有提供的參數。
person.errors.where(:name) # => all name errors.
person.errors.where(:name, :too_short) # => all name errors being too short
person.errors.where(:name, :too_short, minimum: 2) # => all name errors being too short and minimum is 2