'Ruby on Rails - back button that will take you back to the previous page

Is there a way to add a back button to any of my pages that will take you back to the previous page that you were on regardless of what that page is?

So if I have a person on my directors page that landed there from our contracts page it will take them back to contracts, and if a user landed there from our team page it will take them back to team..

Thanks so much

**edit for clarification... If my user lands on the contract page and they submit a form and edit some stuff on the page I'd like them to be able to go back to the previous page but not go back to the form submission or the edit page



Solution 1:[1]

Usually you can use link_to with the symbol :back instead of an URL like this

<%= link_to "Back", :back %>

to return to the previous page.

But this, unfortunately, doesn't work in cases in which you want to skip certain pages (like a page with a form), because :back would simply return you to the previous URL from your history.

If you only want to return to certain pages but not to others then you have to build that functionality on your own. I would start with pushing those pages into the session that you think are worth being on that list. For example like this:

# in the `application_controller.rb`
private

def remember_page
  session[:previous_pages] ||= []
  session[:previous_pages] << url_for(params.to_unsafe_h) if request.get?
  session[:previous_pages] = session[:previous_pages].unique.first(2)
end

# in each controller that is worthy
before_action :remember_page, only: [:index, :show]

Now you will find the previous and the current page in the session if there was already a previous page. And will can return to that previous page with a helper like this

# in a helper
def link_to_previous_page(link_title)
  link_to_if(
    session[:previous_pages].present? && session[:previous_pages].size > 1,
    link_title, 
    session[:previous_pages].first
  )
end

Which can be used in a view like this

<%= link_to_previous_page("return to previous page") %>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1