views:

1475

answers:

3

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) 
yeilds the following:
:back 

Any ideas on How I could get this to work. It seems like a problem that would be easily solved, but I'm new to RoR.

+3  A: 

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[:return_to]
Jaime Bellmyer
This did the trick. Thanks!
easement
+2  A: 

That's how we do it in our application

def store_location
  session[:return_to] = request.request_uri 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 :retrn_to session param, so all forms, even when multiple time POSTed would work with :return_to.

MBO
+1  A: 

I like Jaime's method with one exception, it worked better for me to store 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.

Tony