Demystifying Rails Render

I have seen quite a number of rails programmers getting confused when they use render with :action. For instance your typical edit and update actions,

def edit
@post = Post.find(params[:id])
@tags = @post.tags
respond_to do |format|
format.html
end
end

def update
@post = Post.find(params[:id])
if @post.update_attributes(params[:post])
redirect_to(@post)
else
render :action => :edit
end
end

You’d expect it to render the edit action when the update fails. In essence the specified action is only used to determine which template to render. For this case it will render the view edit.html.erb. Notice though that in our edit function we are setting up the instance variable @tags before rendering the template for that action. So rails will complain that @tags is nil. To take care of this, just set the any instance variables that are needed by that view before calling render like so


def update
@post = Post.find(params[:id])
if @post.update_attributes(params[:post])
redirect_to(@book)
else
@tags = @post.tags
render :action => :edit
end

Advertisements
Tagged , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: