7

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.

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is how you would implement it using the Rails caching. This is not to be confused with instance variable caching though, which the question is about. Upvoted :-)
FYI, use cache_key or cache_key_with_version instead of "user_#{user_id}".
4

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

1 Comment

This approach causes @user_data to grow without bound. Keep your total cache-able dataset size in mind if considering something like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.