简体   繁体   中英

What's the best way to remember params for index in Rails?

Usually, index pages have options for filtering, page, sorting. After going to show, new, edit page, you may want to get back to the index page with the same options as you saw.

To do that, I save the params for index in session.

class ApplicationController < ActionController::Base

  helper_method :index_with_params
  after_filter :save_index_params, :only => [:index]

  def save_index_params 
    session[self.class.to_s] = params 
  end

  def index_with_params overrider={}
    object = self.kind_of?(ApplicationController) ? self : controller
    h = session[object.class.to_s] || {"action" => :index}
    h["only_path"] = true
    url_for(h.merge(overrider));
  end

end

I used to use ActiveRecord for session store. Now I want to use cookie. So session should be light.

How do you handle such a case?

Thanks.

Sam

After going to show, new, edit page, you may want to get back to the index page with the same options as you saw.

If you pass your filtering options in the query string initially ie. example.com/widgets?order_by=price , then when your users navigate back to the index using the browser "Back" button, the filtering options will be preserved.

If you really want the options to be preserved when the user later types in example.com/widgets , then you need to persist the options somewhere , typically in the session object. The cookie store can accommodate up to 4KB so should be fine unless you have a lot of options. If you need more space or performance becomes an issue, look at other session stores, for example Redis Store.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM