0

I was trying to make ruby object invalid in Rails but it's not working. Please see below code:

irb> user = User.first
irb> user.valid? # returns true
irb> user.errors[:base] << 'Making it Invalid'
irb> user.valid? # still returns true

So how is user object still returning as valid even when I added errors to the base. So how can I make my user object invalid in irb ?

2 Answers 2

2

So how is user object still returning as valid even when I added errors to the base?

This is what valid? does under the hood (docs).

# Runs all the specified validations and returns +true+ if no errors were
# added otherwise +false+.
def valid?(context = nil)
  current_context, self.validation_context = validation_context, context
  errors.clear
  run_validations!
ensure
  self.validation_context = current_context
end

As you can see errors.clear is called right before the validations are triggered, that's why it returns true

So how can I make my user object invalid in irb?

The only way I could make it invalid is by forcing an attribute, which has validations on it, to be invalid.

user = User.last
user.valid? # => true
user.email = nil
user.valid? # => false
user.errors.messages # => {:email=>["can't be blank", "is invalid"]}

I see from the comment on the other answer that it's not what you need/want but it's just how it works.

Sign up to request clarification or add additional context in comments.

Comments

1

I think by default the valid? function will clear up the errors for each call. So you cannot append to it, you can try to make one or more attributes to be invalid instead.

3 Comments

How to make attributes invalid ?
Is there any validation on the User class ? If yes, you can make the attributes invalid. Ex: user.name = nil or something.
ok gotcha but that won't solve my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.