'How to add custom errors to the User errors collection?

How can I add errors to the User model manually?

Is it just @user.errors << "some text goes here" ?



Solution 1:[1]

 @user.errors.add(:email, "Not valid")

If you don't want to use any attributes, then in your model

 @user.errors[:base] << "This person is invalid because ..."

For details: link

Solution 2:[2]

WARNING

If you just add errors in a separate method (not in a validation), then by default when you call .valid? or .save those errors will be automatically cleared. So you may want to use validation contexts instead.

Solution 3:[3]

Use the errors.add method

Example:

@user.errors.add(:name, "wasn't filled in")

Solution 4:[4]

try this:

errors.add(:base, "#{user.full_name} has errors here!")

Solution 5:[5]

Expanding on Jason Axelson's answer:

Manually added errors (e.g. errors.add(:email, 'invalid')) will not affect .save or .valid?.

You can use validation contexts to run conditional validations:

class User < ActiveRecord::Base
  validate :ensure_something, on: :special_context

  private

  def ensure_something
    errors.add(:email, 'invalid') if special_condition
  end
end

user.save!(context: :special_context)
user.valid?(context: :special_context)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Said Kaldybaev
Solution 2 Community
Solution 3 Dimitrios Mistriotis
Solution 4 mmike
Solution 5 thisismydesign