Intelligent Redirects: redirect_to_last_index

I often came across the same problem, the user starts say /users?order=email%20desc, chooses the user to edit and when he hits save/destroy he finds himself at /users/, very disturbing…. Another example comes from multiple controllers, when you start in /movies/3 and then, edit the user that created the movie, hit save and you resurface in /users/.

Fixing this redirecting issue was easier then i thought, and i refactored it to be a nice drop in and forget solution!

#app/application_controller.rb
...
  after_filter :save_last_index , :only => :index

protected
  def redirect_to_last_index
    return redirect_to session[:last_index] if session[:last_index]
    redirect_to :action => :index
  end

  def save_last_index
    session[:last_index]=request.request_uri
  end
...

#app/users_controller.rb
  def destroy
    @user = User.find(params[:id]).destroy
    redirect_to_last_index
  end

No more redirecting pain hurray đŸ˜€

Live example

Advertisements

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