'Back' browser action in Ruby on Rails
Ruby on-RailsBrowserRuby on-Rails Problem Overview
Can the 'Back' browser functionality be invoked from a Rails 'Back' link?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
Use
<%= link_to 'Back', :back %>
This is specificied in the RDoc here
This generates some Javascript to navigate backward. I've just tested it, and it works.
Solution 2 - Ruby on-Rails
In Rails 3 and earlier:
link_to_function "Back", "history.back()"
In Rails 4, this method has been removed. See Andreas's comment.
Solution 3 - Ruby on-Rails
This is working in Rails 5.1 along with Turbolinks.
link_to 'Back', 'javascript:history.back()'
Solution 4 - Ruby on-Rails
In Rails 4.2, I got it to work with this:
<a href="javascript:history.back()">Refine Search</a>
I stole this off of @cpm’s answer, except that link_to("Refine Search", :back)
didn’t do the job I wanted while pasting in the generated code <a href="javascript:history.back()">Refine Search</a>
did it perfectly.
Solution 5 - Ruby on-Rails
You can use link_to("Hello", :back)
to generate <a href="javascript:history.back()">Hello</a>
.
Solution 6 - Ruby on-Rails
This will work similarly as browser back button try this
<%= link_to 'Back', 'javascript:history.go(-1);' %>
Solution 7 - Ruby on-Rails
Pay attention to this comment from the user rthbound! As he notes, link_to
with the symbol :back
does not always generate a “real” back event as if the user clicked on their browser’s Back button. It can also be a resubmit of the action that loaded the current view.
The documentation for Rails 4.2.6 says this about link_to
and the :back
symbol:
> Using a :back
Symbol instead of an options hash will generate a link to the
> referrer (a JavaScript back link will be used in place of a referrer if none
> exists).
Solution 8 - Ruby on-Rails
Rails <= 4.0
Using
link_to_function "Back", "history.back()"
seems to be exactly like hitting the back button in the browser. All inputted form data is still there when you get back.
Solution 9 - Ruby on-Rails
If you like me do not want the behaviour of link_to "cancel", :back
you could implement a helper method which either links to the records index path or show path. (i.e teams_path
or team_path(@team)
module CancelFormButtonHelper
def cancel_button(record)
index_path = record.class.to_s.pluralize.downcase + "_path"
path = record.persisted? ? record : eval(index_path)
link_to "Cancel", path
end
end
which can then be used as <%= cancel_button @team %>
within a form for example.
Solution 10 - Ruby on-Rails
You can use js function window.history.back()
= link_to 'Back', onclick: "window.history.back();"