Tuesday, 14 May 2013

redirect_to :back

Long time since my last post I know, but I am mainly cruising along on what I already know with not much new to write about.


Quick trick I discovered today.

  def destroy
    Post.find(params[:id]).destroy
    flash[:notice] = 'Post deleted.'
    redirect_to :back
  end

The redirect_to :back part will send the user back to the page he was on. Useful if a post can be deleted from the post index page or from a user's page, and you want to send back to the right place.

In your functional test you need to set request.env["HTTP_REFERER"], as this is what :back will look at. You can then check it went there. Any strng will do.

 test "should destroy post" do
    request.env["HTTP_REFERER"] = 'origin'
    assert_difference('Post.count', -1) do
      delete :destroy, :id => @post.id
    end
    assert_redirected_to 'origin'
  end

No comments: