Redirecting from CRUD actions to one of many entry points

14/05/2010

When using scaffolding each CRUD action usually has one entry point, the index action. If your CRUD actions (new/create, edit/update and destroy) have multiple entry points which may be the case if you allow editting records from an admin UI (/admin/documents/index), the public UI (/documents/index) and maybe a search UI.

In this case you need to know where to redirect the user back to.

application_controller.rb 

  def bookmark_page
    session[:bookmark] = request.url
  end

  def current_bookmark
    session[:bookmark]
  end

  def redirect_to_bookmark
    redirect_to current_bookmark || root_url
  end

We can called boomark page for any entry point to store the URL and then redirect back to the bookmarked URL in one of our CRUD actions.

admin/documents_controller.rb

def index
  @documents = Document.all
  bookmark_page  
end

We are then redirect back to our entry point, for example:

def update
  if @document.update_attributes(params[:document])
    redirect_to_bookmark
  else
    render :action => :edit
  end
end

Note: If you bookmark a POST request, such as search results, it will also need to be accessible with a GET request.