Rails - caching and permission based views
I use CanCan to check user permissions and display or suppress page content conditionally for my users. I want to cache my pages though, and even with fragment caching can't find an elegant solution... for example:
ca开发者_如何转开发che do
# much code
if can?
# little code
else
# little code
# much code
if can?
# little code
else
# little code
# much code
Surely I'm not alone and there's a good way to do this. What is generally considered the best practice here?
Thanks very much for your input.
I haven't tried this yet, but likely will soon. An approach I'm likely to take is explicitly assigning a cache key based on the relevant models and on the current user. The fragment will be cached separately for each user, but only once per user.
Try some variation on this:
cache ["Unique fragment label", @model.cache_key, current_user.cache_key].join do
# code with and without permissioned elements
end
To ensure that permission changes invalidate the cache, make sure such changes touch the User model's updated_at timestamp. Assuming permissions are stored in a separate model:
class Permission < ActiveRecord::Base
belongs_to :user, :touch => true
end
精彩评论