Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails instance variable caching based on parameters

I am storing users miscellaneous data in user_data table and when I am retrieving that data with the association I defined and then I am actually caching it using Ruby instance Variable caching like this.

def user_data(user_id)
  @user_data || = User.find(user_id).data 
end

but instance variable @user_data will be allocated value only first time when it's nil and once it hold data for a user lets say for user_id equal to 1,and when I am passing user_id 2 in this method it's returning data for user_id 1 , because it will not allocate new value to it so my question is how can I cache it's value based on parameters of function.

like image 311
Subhash Chandra Avatar asked Oct 27 '15 10:10

Subhash Chandra


2 Answers

Take a look at the Caching with Rails guide. Rails can cache data on multiple levels from full page caching to fragment caching, I strongly advise you to read all this page so you can make a perceived choice.

For the low-level caching you can do this:

@user_data = Rails.cache.fetch("user_#{user_id}", expires_in: 1.hour) do
  User.find(user_id).data
end

By default Rails stores cache on disk, but you can setup for memcache, memory store, and etc.

like image 122
Alexey Shein Avatar answered Nov 16 '22 09:11

Alexey Shein


You can use a hash for a key-based intance-variable-cache. I think that does what you want.

def user_data(user_id)
  @user_data ||= {}
  @user_data[user_id.to_i] || = User.find(user_id).data 
end
like image 26
kaspernj Avatar answered Nov 16 '22 09:11

kaspernj