开发者

Memcache basic use in rails 3

开发者 https://www.devze.com 2023-03-26 12:05 出处:网络
So I\'m trying to learn how to use memcache. I installed it in my system. I\'m running it. I installed the dalli gem.

So I'm trying to learn how to use memcache. I installed it in my system. I'm running it. I installed the dalli gem.

All that seems to be just 开发者_运维百科fine.

Lets say I'd like to cache my users table.

I put this in my User.rb file:

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

Then in my controller file, I used to have:

@users = User.where(:group_id => current_user.group_id)

So now I'd like to have something like:

@users = User.all_cached.where(:group_id => current_user.group_id)

I'm getting a no method error for where... Any ideas for how I should accomplish this?


Based on your comment there, I take it you are getting an error like:

undefined method `where' for #<Array:0x00000004d92520>

That's because where works on a model, but when you do User.all, it returns basically an array, and there is no where method defined for an array.

You may want to use the find_all method for enumerables (and arrays) instead (as seen here: http://www.ruby-doc.org/core/classes/Enumerable.html#M001484), or even try a different approach all together. That's your choice.

Here is the example they give to give you an idea off the bat of how it would work:

(1..10).find_all {|i|  i % 3 == 0 }   #=> [3, 6, 9]
0

精彩评论

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