How to redirect to previous page in Ruby On Rails?

easement picture easement · Jan 26, 2010 · Viewed 160.7k times · Source

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 

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.

Answer

Jaime Bellmyer picture Jaime Bellmyer · Jan 26, 2010

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)