Link to the Previous Page in Rails

This is a quick rewrite of an old post. The problem I faced while developing an application was how to link or redirect back to the previous page, without knowing necessarily what that page was. The solution was :back. Here's an example from a controller's perspective:

def destroy
  @post = Post.find(params[:id])

  if @post.destroy
    redirect_to :back
  else
    render :action => "edit"
  end
end

While this example may not make the most sense in the world, it shows how it could be done. I find :back to be more useful in the view, specifically in forms.

<p>
  <%= submit_tag "Submit" %> or
  <%= link_to "Cancel", :back %>
</p>

The use of :back really depends on how a resource is accessed. If the only way to get to the "Create a post" page is through the index action of the posts controller, why use :back? Just <%= link_to "Cancel", posts_path %>.

Here's the definition pulled from the Ruby on Rails docs:

:back - Back to the page that issued the request. Useful for forms that are
triggered from multiple places. Short-hand for
redirect_to(request.env["HTTP_REFERER"])

I hope this helps.

Filed in Tutorials.