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

Time:02-03

Here's a code fragment from a Rails project I am working on:

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

The documentation for the ActiveRecord::Error class and the Active Record Validation Guide both explain message, but neither explain type. What is type, what impact does it have on validation errors, and where is it documented?

CodePudding user response:

https://api.rubyonrails.org/classes/ActiveModel/Errors.html contains some information on it:

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.

  •  Tags:  
  • Related