开发者

Rails 3: caches_action and root :to problem

开发者 https://www.devze.com 2023-03-19 05:02 出处:网络
So I use caches_action :page in my Public controller. In my routes.rb I point root :to => \"public#page\"

So I use caches_action :page in my Public controller. In my routes.rb I point root :to => "public#page" . The page action contains this line: @pictures = Picture.paginate :page => params[:id] || 1, so that normally the root path always shows the page action with the very first portion of pictures. My problem is that after I started to use cache, root sometimes displays the page action, but not with the id=1, but with another id (I guess it's just another cached 'page'), so that the pictures shown on root are not the newest ones.

开发者_StackOverflow社区How can I set it up so that root will always point to cached :controller => public, :action => page, :id => 1?


Action caching doesn't work with params (it ignores them). You might try using JavaScript to extract the id from the URL and load the pictures via AJAX.

If you truly want to cache pages by the parameters then you will need to add custom logic to read/write the cache files.

EDIT: Caching doesn't consider query string parameters

UPDATE:

I think what you want to do is described here: Rails action caching with querystring parameters


I had this same problem. I've found two good ways to solve it. Option 1 will store a copy of all customized requests in your cache. If your site has a lot of searches that won't be repeated, or your concerned about memory space, this isn't ideal. Option 2 only caches pages without parameters.

1) As "Wizard of Ogz" linked to, you can use :cache_path to include the parameters in the cache key, so that pages with parameters are cached separately from the no-parameter request.

caches_action :page,
  :cache_path => proc {|c|
    {:tag => c.params}
  }

2) You can use :if to pass a proc and not cache the action at all if parameters are present. This will keep custom searches out of your cache memory.

caches_action :page,
 :if => proc {
    params.blank?
  }

If it's a url other than your root, you can delete the controller and action params:

caches_action :page,
 :if => proc {
    updated_params = params.delete_if { |k,v| ['controller', 'action'].include?(k) }
    updated_params.blank?
  }

Here's the corresponding API info: http://api.rubyonrails.org/classes/ActionController/Caching/Actions.html


Following on from the answer from the wizard of ogz - you might want to take a different approach here and instead of using action caching, set up a method in your picture class that returns you the newest pictures, cache the result of that method, and then update the cache when new pictures are loaded. Then you could do something like

@pictures = params[:id] ? {(Picture.paginate :page => params[:id]) : (Rails.cache.fetch('Picture.new_ones'){Picture.paginate :page => 1})
0

精彩评论

暂无评论...
验证码 换一张
取 消