开发者

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" ?


 @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


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.


Use the errors.add method

Example:

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


try this:

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


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜