RoRprog978
RoRprog978

Reputation: 5

Ruby on Rails Exception usage

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

Upvotes: 0

Views: 165

Answers (1)

M.Elkady
M.Elkady

Reputation: 1133

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

Upvotes: 1

Related Questions