0

I put many question about caching in here but no one answer. So mayby i will have answer on this.

I have in my search model code like this:

users = users.where('id >?', my_value)

Rails.cache.fetch('my_cached',expires_in: 3.minutes) do

    users = users.order('current_sign_in_at DESC')

end

Can somebody explain me what this do. I thought that this will return sorted users table and put it in cache for 3 minutes so when i require next search it will return me my_cached result if it doesnt expired.

But it does not work like that. When some user login and current_sign_in_at is changed - cache is override and new query is returned.

Wordica
  • 2,427
  • 3
  • 31
  • 51
  • I think cache is disabled in development mode by default? this might be helpful - http://stackoverflow.com/questions/5636299/rails3-caching-in-development-mode-with-rails-cache-fetch?answertab=active#tab-top – house9 Sep 01 '13 at 17:34

1 Answers1

0

I am not very experienced with the caching procedure for RoR, but I think what you say is right.

I thought that this will return sorted users table and put it in cache for 3 minutes so when i require next search it will return me my_cached result if it doesnt expired.

Then, I think that the caching should be done in this matter:

Rails.cache.fetch('my_cached',expires_in: 3.minutes) do
    User.where('id >?', my_value).order('current_sign_in_at DESC')
end

Remember, that can exist some rules that can expire the cache before the expiration time assigned. This depends how the User model is configured.

Again, the query will not be executed only if you use the variable my_cached. Maybe the query you see is coming from another procedure (maybe from Devise itself if you use it?)

SOME HELPFUL REFERENCE

UPDATE

If the variable my_value changes frequently (can be an aleatory value), then the cache will be used only if the my_value is the same as a previous (in 3 minutes) value.

Maybe an alternative solution for a variable my_value can be:

Rails.cache.fetch('my_cached',expires_in: 3.minutes) do
    User.all # cache all users
end
# then filter the cached value by the my_value and order it
damoiser
  • 6,058
  • 3
  • 40
  • 66
  • im reading about it and if i understand this only return scope for activerelation ,so when next search is made scope change and rails save it in cache. I must do something else - saving ID for users in cache and then in view display users with returned id – Wordica Sep 01 '13 at 16:13
  • @Michael if I have understand correctly what you want to do, I have updated my answer – damoiser Sep 01 '13 at 17:07