When browsing various projects, I noticed two ways to write a saving feature.
1)
def create
if @post.save
flash[:notice] = "Success"
redirect_to :action => "index"
else
render :action => "new"
end
2)
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?
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...
When browsing various projects, I noticed two ways to write a
saving feature.
1)
def create
if @post.save
flash[:notice] = "Success"
redirect_to :action => "index"
else
render :action => "new"
end
2)
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?
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.
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.