0

Upon finding a failed validation, invalid? will return false and exit. If all validations pass, invalid? will return true and the code will continue. Does the rescue code only run if all validations pass? If so, what raised errors will it catch? Lastly why is there no Begin?

    def save
      return false if invalid? # invalid? triggers validations
      true
      rescue ActiveRecord::StatementInvalid => e
      # Handle exception that caused the transaction to fail
      # e.message and e.cause.message can be helpful
      errors.add(:base, e.message)
      false
    end

1 Answer 1

1

Does the rescue code only run if all validations pass? Blockquote

No, it will run if the call of invalid? throws an exception of type StatementInvalid

what raised errors will it catch? Blockquote

the call of invalid? here is what raises the error

why is there no Begin?

in ruby, you can remove begin if you rescue from any exception that is raised from methods body so

 def method 
  begin 
   #some code
   rescue
   #handle 
  end 
 end

equal to

 def method 
   some code
   rescue  
   # handle 
 end

but the second syntax shorter and cleaner

Note: it doesn't same right to me to rescue from ActiveRecord::StatementInvalid inside an override to save

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

3 Comments

can invalid? throw a StatementInvalid exception even if all validations pass?
it's possible but this may be aBug that's why I said it's not right code. StatementInvalid is a database execution error. that's mean wrong database query. why do you need to rescue from such error?
I found that code in a well written rails tutorial that I can't find at the moment. It's used on models with "include ActiveModel::Model" and don't inherit from ApplicationRecord. It works well in my app. Now I understand it more. Thanks

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.