Jwan622
Jwan622

Reputation: 11659

How to cache my tag_counts for acts_as_taggable_on.

I have this in an erb file>

<%= select_tag :catalog_item_submission_tag, options_for_select(Submission.tag_counts.order('name ASC').map {|t| [t.name, t.name]}, params[:catalog_item_submission_tag]), include_blank: true, class: 'select2ify allow-clear' %>

and I'd like to cache it because the tag counts are huge and are costing my site time:

Submission.tag_counts.count
 => 23399

And they don't change that often (maybe a cache that expires once every 4 hours is sufficient). Is there a way to do this using the acts_as_taggable_on gem?

For reference, the submission has tags:

class Submission < ActiveRecord::Base
  searchkick

  acts_as_taggable_on :tags

Upvotes: 0

Views: 150

Answers (1)

Mahys116
Mahys116

Reputation: 538

You just need to wrap your code in Rails.cache.fetch, like that:

class Submission < ActiveRecord::Base
  searchkick

  acts_as_taggable_on :tags

  def self.cashed_tags_counts
    Rails.cache.fetch("cashed_tags", expires_in: 4.hours) do
      tag_counts.order('name ASC').map {|t| [t.name, t.name]}
    end
  end
end

Here is more information about it

Upvotes: 1

Related Questions