Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails: force a model to be not valid

I have a very specific situation where I want to force an instance of a model not valid.

Something like this:

user = User.new
user.valid? #true
user.make_not_valid!
user.valid? #false

Any way to achieve that?

Thanks!

like image 400
bymannan Avatar asked Feb 12 '23 21:02

bymannan


1 Answers

You can do:

validate :forced_to_be_invalid

def make_not_valid!
  @not_valid = true
end

private

def forced_to_be_invalid
  errors.add(:base, 'has been forced to be invalid') if @not_valid
end
like image 161
BroiSatse Avatar answered Feb 15 '23 11:02

BroiSatse