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

Tagged , , , , ,
Follow

Get every new post delivered to your Inbox.