开发者

Trouble on caching an action when I rewrite a URL

I am using Ruby on Rails 3 and I have an issue on caching when I rewrite a URL in the model using the to_param method.

In my User model I have:

class User < ActiveRecord::Base
  def to_param # Rewrites URL
    "#{self.id}-#{self.name}-#{self.surname}"
  end

  ...
end

In the User controller I have:

class UsersController < ApplicationController
  caches_action :show

  def show
    ...
  end
end

In the Users sweeper I have:

class UsersSweeper < ActionController::Caching::Sweeper
  observe User

  def after_save(user)
    clear_users_cac开发者_开发知识库he(user)
  end

  def after_destroy(user)
    clear_users_cache(user)
  end

  def clear_users_cache(user)
    expire_action :controller => :users, :action => :show, :id => user
  end
end

Now, when I browse the user show page in the log file I get:

Write fragment views/<my_site_name>/users/2-Test_name-Test_surname (0.3ms)

When I expire the cache after a change the name or surname in the log file I get

Expire fragment views/<my_site_name>/users/2-New_test_name-New_test_surname (0.3ms)

So, since the data is changed, it doesn't expire the cache because Rails try to expire 2-New_test_name-New_test_surname and not 2-Test_name-Test_surname.

How can I "easly" handle the Rails caching behavior to make it to work?


P.S.: Of course if I don't use the to_param method, it works as well.


UPDATED

I can do something like this

caches_action :show, :cache_path => Proc.new { |c| 'users/' + c.params[:id].split('-').first }

but I don't think that is a good way to solve things...


Try using a custom path:

You can set modify the default action cache path by passing a :cache_path option. This will be passed directly to ActionCachePath.path_for. This is handy for actions with multiple possible routes that should be cached differently. If a block is given, it is called with the current controller instance.

caches_action :show, :cache_path => { :project => 1 }

Obviously customize to suit your needs. See the API for more info.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜