Manually copying instances of Ruby on Rails instances based on parameters

I store user different data in the user_data table, and when I get this data with the association definition that I defined, and then I actually cache it using a Ruby instance with a variable cache instance like this.

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

but the @user_data instance @user_data will only be assigned a value the first time it is zero, and after it stores the data for the user, let's say that for user_id is 1, and when I pass user_id 2 in this method, it returns the data for user_id 1, because it will not allocate a new value for it, so my question is how can I cache its value based on function parameters.

+5
source share
2 answers

See Caching with Rails . Rails can cache data at several levels from full page caching to fragment caching, I highly recommend that you read this entire page so that you can make your intended choice.

For 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 the cache on disk, but you can configure it for memcache, memory, etc.

+7
source

You can use the hash for the intance-variable-cache key. 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 
+2
source

Source: https://habr.com/ru/post/1234595/


All Articles