BC00
BC00

Reputation: 1639

Rails: Controlling browser back button

I have a users index action that directs a person to different pages depending on the params. Currently when a user passes in search params and I render the custom view template, when a person clicks on a user it goes to their user edit page. I want the back button on the browser to go back to the custom view if thats where the user came from. However, it keeps going back to the users index regardless.

What should I be doing to make the browser back button go back to the last page a user came from?

My controller code is:

def index
  @criteria = params[:criteria]
  respond_to do |format|
    format.js {
      unless @criteria.blank? || @criteria.length < 3
        @results = fire(@criteria) 
        render :template =>'admin/users/search_user', :object =>  @results, :locals => { :autocomplete => true, :criteria => @criteria }
      else
        @users = User.paginate :page => params[:page], :order => "users.created_at desc"
        render :template =>'admin/users/users', :object =>  @users, :locals => { :autocomplete => true, :criteria => @criteria }
      end
    }
    format.html {
        @users = User.paginate :page => params[:page], :order => "users.created_at desc"
    }
  end
end

This is my understanding of the flow:

  1. user clicks on users link
  2. routes defaults to users index
  3. action loads data and renders template
  4. template displays
  5. user types in search params
  6. the html form makes the search term go in critera which goes in params
  7. enter by default from browser submits
  8. submit points to same action since theres no custom route?
  9. since params has criteria the search results/template is rendered
  10. click on user, takes you to user edit
  11. click back button on browser, browser knows the page list to be the users index as last stop since search results are not a seperate URL and the HTML is rendered with Javascript?
  12. need to get the browser to redirect to the search results template somehow

Thanks!

Upvotes: 2

Views: 6031

Answers (3)

RAJ
RAJ

Reputation: 9747

Try <%= link_to 'Back', 'javascript:history.go(-1);' %>. It will give you exactly same functionality as browser's back button.

Upvotes: 4

Alex Lynham
Alex Lynham

Reputation: 1318

What you're describing is basically friendly forwarding. You can't override the browser's default behaviour in that case (unless you want to go down a deep rabbit hole of JavaScript), but you could achieve something user friendly by following a similar pattern to this:

http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users#sec-friendly_forwarding

Hope that helps, anyway.

Upvotes: 0

Stejsky
Stejsky

Reputation: 103

Not sure, if I understand you correctly, but this could solve your problem, maybe

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

Upvotes: 1

Related Questions