spyd3rr
spyd3rr

Reputation: 3085

Using rescue on assignment in Rails

I'm trying to rescue from a fault that might happen upon an assignment. I can rescue from nil no problem, but what if I want to take a couple actions?

For example, this works fine:

new_object = Product.find_by_id(412) rescue nil

However, I want to print something and take another action. So how would I get something like this to work:

new_object = Product.find_by_id(412) rescue nil
                                        puts "what happened"
                                        next
                                     end

Upvotes: 0

Views: 437

Answers (2)

MorphicPro
MorphicPro

Reputation: 2902

begin
  foo = Product.find_by_id!(412)
rescue ActiveRecord::RecordNotFound
  logger.warn "Could not find foo" 
end

Upvotes: 0

jvnill
jvnill

Reputation: 29599

use the following

begin
  new_object = Product.find_by_id(412)
rescue
  new_object = nil
  puts 'what happened'
  next
end

Upvotes: 2

Related Questions