Is there a way to cache a generic call?

For example, I have it in the index controller

@users = User.current

this is my user model

 scope :current, :conditions => { :active => true }, :order => 'LOWER(first_name), LOWER(last_name) ASC'

Which basically captures all the records, and I don't paginate, because I use a djatables jquery table that has an excellent filter search ... the problem I want to achieve is to cache them if possible, if there are no new users ... which does not happen very often

I read about fresh_when but didn't know what could be used here

UPDATE

After the answer below, I do not see CACHE in the log that I see

  Company Load (0.4ms)  SELECT `companies`.* FROM `companies` INNER JOIN `positions` ON `companies`.`id` = `positions`.`company_id` WHERE `positions`.`user_id` = 551
  Company Load (0.4ms)  SELECT `companies`.* FROM `companies` INNER JOIN `positions` ON `companies`.`id` = `positions`.`company_id` WHERE `positions`.`user_id` = 93
  Company Load (0.4ms)  SELECT `companies`.* FROM `companies` INNER JOIN `positions` ON `companies`.`id` = `positions`.`company_id` WHERE `positions`.`user_id` = 668
+5
source share
1 answer
class User < ActiveRecord::Base
  after_save :clear_cache

  def self.current
    Rails.cache.fetch("current_users", expires_in: 1.hour) do
      User.where(active: true).order("LOWER(first_name), LOWER(last_name) ASC").all
    end
  end

private

  def clear_cache
    Rails.cache.delete("current_users")
  end

end

Make sure caching is enabled in config / environment / *. rb:

config.action_controller.perform_caching = true

, . :
http://robotmay.com/post/23161612605/everyone-should-be-using-low-level-caching?bda26d48
http://www.tmatthew.net/blog/rails-caching-example
http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-fetch

, , . , , (application_controller.rb):

before_filter :load_models_if_dev
def load_models_if_dev
    if Rails.env == 'development'
        User; Post; Comment # whatever other classes that can get cached.
    end
end 

UPDATE
.all User.where().order().all. , , ActiveRecord, . .all . @Frederick Cheung , .

+6
source

All Articles