198

I have a page that lists all of the projects that has sortable headers and pagination.

path:
/projects?order=asc&page=3&sort=code

I choose to edit one of the projects

path:
projects/436/edit

When I click save on that page, it calls the projects controller / update method. After I update the code I want to redirect to the path that I was on before I clicked edit a specific project. In other words, I want to be on the same page with the same sorting.

I saw link_to(:back) and thought that :back may work in redirect_to(:back), but that's a no go.

puts YAML::dump(:back) 
yields the following:
:back 

How can I get this to work?

9 Answers 9

342

In your edit action, store the requesting url in the session hash, which is available across multiple requests:

session[:return_to] ||= request.referer

Then redirect to it in your update action, after a successful save:

redirect_to session.delete(:return_to)
6
  • 21
    doesn't having several tabs open confuse this logic?
    – jones
    Commented Jan 22, 2013 at 11:19
  • 13
    Couldn't you just redirect_to request.referer?
    – Elle Mundy
    Commented Apr 24, 2014 at 16:01
  • 1
    @DanMundy No, for it to work it should be request.referer.referer, if that could be possible. @Jaime Bellmyer Why ||=?
    – x-yuri
    Commented May 27, 2015 at 17:33
  • @jones yes. There is also confusion if you switch to another model edit. I'm also interested in why ||=
    – Mauro
    Commented Aug 29, 2016 at 15:25
  • 1
    Doesn't make any sense to use ||= since you do want to overwrite the variable, otherwise you won't have the latest page visited.
    – pmrotule
    Commented Mar 9, 2018 at 10:11
106

Why does redirect_to(:back) not work for you, why is it a no go?

redirect_to(:back) works like a charm for me. It's just a short cut for redirect_to(request.env['HTTP_REFERER'])

http://apidock.com/rails/ActionController/Base/redirect_to (pre Rails 3) or http://apidock.com/rails/ActionController/Redirecting/redirect_to (Rails 3)

Please note that redirect_to(:back) is being deprecated in Rails 5. You can use

redirect_back(fallback_location: 'something') instead (see http://blog.bigbinary.com/2016/02/29/rails-5-improves-redirect_to_back-with-redirect-back.html)

5
  • 12
    redirect_to :back does not work well for me either, say you visit /posts/new, this is set as the referer for the next request, so after the form is successfully submitted it shows the form again, i.e /posts/new. It does however work well for other purposes.
    – Kris
    Commented Feb 1, 2012 at 16:15
  • That is, OP wants to redirect back twice. I bet he could just redirect_to projects_path.
    – x-yuri
    Commented Apr 20, 2015 at 20:12
  • Yeah. redirect_back does not work as well in Rails 5
    – strizzwald
    Commented Dec 18, 2017 at 14:36
  • @strizzwald what does "does not work well" mean? Any details?
    – Pascal
    Commented Jan 14, 2018 at 12:06
  • @pascalbetz, What I meant is that if HTTP_REFERER is not set, you may get ActionController::RedirectBackError, you would have to rescue from this exception in that case. From my understanding, using redirect_back does not require any exception handling since you are forced to provide fallback_location. Maybe 'does not work well' is not the right way to put it.
    – strizzwald
    Commented Jan 15, 2018 at 7:47
46

I like Jaime's method with one exception, it worked better for me to re-store the referer every time:

def edit
    session[:return_to] = request.referer
...

The reason is that if you edit multiple objects, you will always be redirected back to the first URL you stored in the session with Jaime's method. For example, let's say I have objects Apple and Orange. I edit Apple and session[:return_to] gets set to the referer of that action. When I go to edit Oranges using the same code, session[:return_to] will not get set because it is already defined. So when I update the Orange, I will get sent to the referer of the previous Apple#edit action.

1
  • yes, but can you suggest what to do if accidentally same url was stored as you are at? You are at apple and you came from apple. And you want previous location
    – Uko
    Commented Sep 18, 2013 at 14:53
35

This is how we do it in our application

def store_location
  session[:return_to] = request.fullpath if request.get? and controller_name != "user_sessions" and controller_name != "sessions"
end

def redirect_back_or_default(default)
  redirect_to(session[:return_to] || default)
end

This way you only store last GET request in :return_to session param, so all forms, even when multiple time POSTed would work with :return_to.

1
  • 3
    yup that's pretty good. I would only suggest to generally not useand and or in if statements. Use && and || instead. Details here.
    – Achilles
    Commented Dec 28, 2015 at 13:24
26

In rails 5, as per the instructions in Rails Guides, you can use:

redirect_back(fallback_location: root_path)

The 'back' location is pulled from the HTTP_REFERER header which is not guaranteed to be set by the browser. Thats why you should provide a 'fallback_location'.

3
  • This feature appears in rails 5.
    – Chambeur
    Commented Aug 4, 2016 at 6:48
  • @pSkarl How can I pass a notice object with the redirect_back statement in order to tell the user something went wrong with a flash message? Commented Dec 12, 2016 at 5:54
  • 2
    Well, I could solve this by doing: redirect_back(fallback_location: root_path, notice: "Something went wrong!"). Hope it could help somehow. Commented Dec 12, 2016 at 6:10
18

request.referer is set by Rack and is set as follows:

def referer
  @env['HTTP_REFERER'] || '/'
end

Just do a redirect_to request.referer and it will always redirect to the true referring page, or the root_path ('/'). This is essential when passing tests that fail in cases of direct-nav to a particular page in which the controller throws a redirect_to :back

1
  • Not sure which file you were looking at but at the rack source, this is how referer was defined as of 28 Mar 2011, and that is how it is defined as of today. That is, || '/' is not part of the definition.
    – maček
    Commented Dec 2, 2013 at 6:35
2
link_to 'get me back', :back

The symbol :back is your swiss army knife.

0
1

For those who are interested, here is my implementation extending MBO's original answer (written against rails 4.2.4, ruby 2.1.5).

class ApplicationController < ActionController::Base
  after_filter :set_return_to_location

  REDIRECT_CONTROLLER_BLACKLIST = %w(
    sessions
    user_sessions
    ...
    etc.
  )

  ...

  def set_return_to_location
    return unless request.get?
    return unless request.format.html?
    return unless %w(show index edit).include?(params[:action])
    return if REDIRECT_CONTROLLER_BLACKLIST.include?(controller_name)
    session[:return_to] = request.fullpath
  end

  def redirect_back_or_default(default_path = root_path)
    redirect_to(
      session[:return_to].present? && session[:return_to] != request.fullpath ?
        session[:return_to] : default_path
    )
  end
end
1
  • Will these not return you to a different path when you are editing 2 or more items?
    – gekong
    Commented Mar 19, 2021 at 10:42
0

I wonder if this will work

  def edit
    if request.referer != request.original_url
        @return_here =  request.referer
    end

  end

and use @return_here as a hidden value in the submit form.

of course reloading will kill this so just go back to a default fall back as needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.