Can someone help me with the following code? I’m purposely typing in a
bogus rga number, and the begin/rescue block should catch that and
inform the user, right?
But when I run this with a bogus number, I get the “Render and/or
redirect were called multiple times in this action” error.
if request.post?
rga_number = params[:rga_number]
user_id = params[:user_id]
begin
rga = Rga.find(params[:rga_number])
rescue
flash[:notice] = 'There is not a RGA with that number'
redirect_to :action => 'list'
end
new_RGA = RgaEvent.new
new_RGA.rga_id = rga_number
new_RGA.rga_number = rga_number
new_RGA.user_id = user_id
if new_RGA.save
user_name = User.find(user_id).name
flash[:notice] = 'RGA assigned to user ' + user_name
redirect_to :action => 'list'
end
Can someone help me with the following code? I’m purposely typing in a
bogus rga number, and the begin/rescue block should catch that and
inform the user, right?
It does; that’s not the problem.
if request.post?
rga_number = params[:rga_number]
user_id = params[:user_id]
begin
rga = Rga.find(params[:rga_number])
rescue
flash[:notice] = 'There is not a RGA with that number'
redirect_to :action => 'list'
You need to “return” right here, or execution continues on. That’s why
you’re getting the error message.
You probably should rescue ActiveRecord::RecordNotFound. If a
different exception were to be raised, you would never know it.
begin
rga = Rga.find(params[:rga_number])
rescue ActiveRecord::RecordNotFound
flash[:notice] = ‘There is not a RGA with that number’
redirect_to :action => ‘list’
end
Still getting the error. You’re dealing with a newbie here: What do
you mean by ‘return’?
one, so I’m still confused as to why this case required a return in
it.
This has nothing to do with begin/rescue. It has everything to do with
the fact that you should redirect or render precisely once per action,
whereas in you original code you would end up doing a redirect in the
rescue block and then again if bit below.
you should redirect or render precisely once per action,
How do you possibly check for multiple errors in an action? Aren’t
you
supposed to redirect after detecting one?
OK, so at a basic level, this will result in the double render error
will also cause errors unless the 2 conditions are mutually exclusive
You need to do something like. Either return after redirecting/
rendering or do whatever you have to do to ensure that you don’t do
it more than once per action, for example
def foo
if …
redirect_to :action => ‘bar’
return
end