ActiveRecord::Error.type 如何影响验证错误消息?

How does ActiveRecord::Error.type affect validation error messages?

这是我正在从事的 Rails 项目的代码片段:

if has_youtube && has_vimeo
  record.errors.add(:video_link, type: 'A project cannot have videos from both YouTube and Vimeo')
  return
end

if record.video_link.present?
  record.errors.add(:video_link, message: "This doesn't look like a valid YouTube or Vimeo link. Please try again.")
else
  record.errors.add(:video_link, :blank, message: 'You need to complete this field to register.')
end

ActiveRecord::Error class and the Active Record Validation Guide 的文档都解释了 message,但都没有解释 type。什么是 type,它对验证错误有什么影响,它记录在哪里?

https://api.rubyonrails.org/classes/ActiveModel/Errors.html 包含一些关于它的信息:

add(attribute, type = :invalid, **options) Adds a new error of type on attribute. More than one error can be added to the same attribute. If no type is supplied, :invalid is assumed.

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"]}

If type is a string, it will be used as error message.

If type is a symbol, it will be translated using the appropriate scope (see 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)"]

If type is a proc, it will be called, allowing for things like Time.now to be used within an error.

If the :strict option is set to true, it will raise ActiveModel::StrictValidationFailed instead of adding the error. :strict option can also be set to any other exception.