开发者

Using memcache in rails 3 for a set of records

I'm trying to understand how to properly use memcache in my rails app.

Currently, in my header view of my app, I have a conditional like 开发者_如何转开发so:

<% if current_user.company.stats == true %>

So everytime any page loads, its hitting the database to check if the current user's company has statistics enabled.

This of course seems crazy to me.

So my question is, how should I be using memcache to resolve this. Companies rarely change, so data relating to them should be cached.

I understand something like this would cache them all:

  def self.all_cached
    Rails.cache.fetch('Company.all') { all }
  end

But I know thats not what I need here - right?


Memcached can be seen as a big map key-value.

You should write something like this in your view:

 <% if stats_enabled?(current_user.company) %>

And then write an helper method (on ApplicationHelper, for example):

def stats_enabled?(company)
  Company.stats_enabled?(company) 
end

and an cache method on you model:

class Company < ActiveRecord::Base
  ...
  def self.stats_enabled?(company) 
     return Rails.cache.fetch(company.id) {
        Company.find(company.id).stat
     }
  end
  ...
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜