views:

24

answers:

3
def update 
 @user = User.find(params[:id]) 
 if @user.update_attributes(params[:user])
      render :action => show
  end
      render :template => "fix_user_errors"
end

The previous code will generate an error (because render is called twice) in the case where update_attributes succeeds. The act of calling render (and redirect_to) should somehow terminate the processing of an action?But its not why?

+1  A: 

render doesn't actually terminate the processing of the action.

You need to add an else to your if statement:

if @user.update_attributes(params[:user])
  render :action => show
else
  render :template => "fix_user_errors"
end

I think you can also use "return render ..." which will return immediately from the action method but this might have unintended consequences.

Toby Hede
Yaa return statement works.. Thanks.. I got the point...!!!
piemesons
A: 

No, calling render does not end your action. render is a method to tell your controller which template is going to render if you do not want the default one, not to actually tell it you are done processing.

You might want to call return after you call render, if you are actually done.

Also, calling redirect (I am guessing this, I am not sure) actually sends a Location header to your browser, but does not end your action. You need to return or branch too after calling it, so you do not call it twice.

Francisco Soto
A: 

You can use the else, doesnt really has sense to render an action and render another. I would write like this:

def update 
  @user = User.find(params[:id]) 
  if @user.update_attributes(params[:user])
    redirect_to :action => show
  else
    render :template => "fix_user_errors" #probably you want to render the edit template here.
  end
end
dombesz