rails caching: expire_action in another namespace
My application is using a namespace for administrati开发者_Python百科ve purposes. I recently tried to start using action caching however I ran into some problems trying to expire the cache using expire_action. Basically I have a index action in my default namespace newsposts controller that is cached using action caching like this:
class NewspostsController < ApplicationController
caches_action :index, :layout => false
def index
@posts = Newspost.includes(:author).order("created_at DESC").limit(5)
end
end
This caches the view under views/host/newsposts.
The default namespace has no actions for modifying data, they are all in my admin namespace. In my Admin::NewspostsController I am trying to expire this cache in the create action like this:
expire_action(:controller => 'newsposts', :action => 'index')
however this will expire a cache file located under views/host/admin/newsposts. Obviously it can not work since im in the admin namespace and rails is (rightfully) looking to expire cache for this namespace. Sadly I can not pass a namespace parameter to the axpire_action method, so how can i expire the action cache in another namespace?
after some more digging I finally found the solution. It's a bit hinted in the url_for method:
In particular, a leading slash ensures no namespace is assumed. Thus, while url_for :controller => 'users' may resolve to Admin::UsersController if the current controller lives under that module, url_for :controller => '/users' ensures you link to ::UsersController no matter what.
So basically,
expire_action(:controller => '/newsposts', :action => 'index')
Will expire in the default namespace, and
expire_action(:controller => 'admin/newsposts', :action => 'index')
in the admin namespace (when in default).
RailsCast
One additional note I learned, if you want to expire a specific format, such as XML, JSON, etc., just
expire_action(:controller => '/newsposts', :action => 'index', :format => 'xml')
or whatever format you want. It look me a while to figure out.
精彩评论