"save! and rescure" or if-else

When browsing various projects, I noticed two ways to write a saving
feature.

def create
if @post.save
flash[:notice] = “Success”
redirect_to :action => “index”
else
render :action => “new”
end

def create
@post.save!
flash[:notice] = “Success”
redirect_to :action => “index”
rescue
render :action => "new
end

Which is better? What’s the pros and cons for each usage?

-T

end
end

Which is better? What’s the pros and cons for each usage?

An advantage for 1 is that if you did say “x = 1 / 0” an error would be
raised and you’d har about it. In 2 that error would be rescued and
you’d
never know you had a problem. Granted that’s a bogus example, but
replace
1 and 0 with variables and it can happen.

An advantage for 2 is that you’ll catch all the errors so if you really
don’t want to handle them individually you can simplify your could.

That said, if going with option two, you may want to rescue the specific
exception thrown when the save fails, and allow others to bubble up…

-philip

On 21 May 2008, at 04:41, Philip H. wrote:

else
rescue
replace
1 and 0 with variables and it can happen.

Yup, an unqualified rescue can be a nasty thing. I’d also add that I
like to think of exceptions as for exceptional things (weird errors, a
database deadlock etc…) The user fat-fingering something isn’t
something like that.

Fred

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs