March 22

0 comments

Going back two pages in Ruby on Rails

By Christopher Mendla

March 22, 2016


Last Updated on November 30, 2019 by Christopher G Mendla

I had a situation where I had a list of records with edit buttons. After editing a record, the normal course of things is to show the document. The user wanted an easy way to get back to the list.

The list was the result of a combination of searching, sorting and pagination. They would hit the update page, then the show page. This precluded a simple redirect_to :back.

The solution was the following code.

 

<% if session[:administrator] || session[:full] then %>
<%= button_tag “Back to list”, type: ‘button’, onclick: ‘window.history.go(-2)’ %>
<% end %>

 

The if statement will only show the button if the user is an admin or full user since read only users cannot edit anyway.

The button_tag will pass Javascript on a click . The Javascript simply says to go back 2 windows in the windows stack. In this particular application, this worked fine. There may be cases such as carts where this won’t work.

Summary
1. The user is on a searched, sorted, paged list.
2. They click an edit icon.
3. The edit screen comes up and they make the appropriate changes.
4. When they click submit, the show screen appears with the button
5. Clicking the button takes them back 2 levels.

One minor issue here from a usability standpoint is that the button will appear when the user creates a new record. However, there will be at most three users adding records so this can be handled with 15 seconds of training. The other solution would be to set a flag when coming from the create method and then not showing the button.

For more information about stacks, see

https://developer.mozilla.org/en-US/docs/Web/API/History_API#Moving_to_a_specific_point_in_history

 


Christopher Mendla

About the author

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}