Wordica
Wordica

Reputation: 2597

Rails caching all query

I have that kind of script.

Search_controller.rb :

def results
   @users = @search.cached_users_count.page(params[:page]).per_page(10)
end

Search.rb Model :

users = users.order('current_sign_in_at DESC')  


def cached_users_count

    Rails.cache.fetch(["user_count", expires_in: 5.minutes]) { users }

end

What i want to do is cache all query because when some user will login after search results are executed, will_paginate replace results on next page - because just logged user go on first position and results are changed for order by current_sign_in_at

Can somebody help me with that ? Right now no cache is made , for every search results theres is sql response.

Upvotes: 0

Views: 812

Answers (1)

chucknelson
chucknelson

Reputation: 2336

There are a few things to change in your current implementation to get the behavior you're looking for.

  1. The users object you're starting with is returning a relation, but only the scope, which means it is not storing results as you expect. To store the results of the query you'll need to load them using a query method. Use all if in Rails 3, or load if in Rails 4:

    users.order('current_sign_in_at DESC').all  #Rails 3
    users.order('current_sign_in_at DESC').load #Rails 4, all is deprecated
    
  2. The syntax for the Rails cache is incorrect if you really want it to expire. You're passing expires_in as part of the key, which is an array [] in your current code. You want to just pass normal parameters, with expires_in as an option.

    Rails.cache.fetch("user_count", expires_in: 5.minutes) { users }
    

See the following for a similar question on SO as well: Confusion caching Active Record queries with Rails.cache.fetch

Upvotes: 2

Related Questions