Home > Blockchain >  How to make object invalid in Ruby on Rails?
How to make object invalid in Ruby on Rails?

Time:12-02

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 ?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related