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?
>Solution :
https://api.rubyonrails.org/classes/ActiveModel/Errors.html contains some information on it:
add(attribute, type = :invalid, **options) Adds a new error of
typeonattribute. More than one error can be added to the same
attribute. If notypeis supplied,:invalidis 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
typeis a string, it will be used as error message.If
typeis a symbol, it will be translated using the appropriate scope
(seegenerate_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
typeis a proc, it will be called, allowing for things like
Time.nowto be used within an error.If the
:strictoption is set totrue, it will raise
ActiveModel::StrictValidationFailedinstead of adding the error.
:strictoption can also be set to any other exception.