如何为act_as_taggable_on缓存我的tag_counts。

时间:2018-10-11 17:59:11

标签: ruby-on-rails caching

我在erb文件中有这个>

<%= 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' %>

,我想将其缓存,因为标签数量巨大,并且浪费了我的网站时间:

Submission.tag_counts.count
 => 23399

并且它们不经常更改(也许每4小时过期一次的缓存就足够了)。有没有办法使用acts_as_taggable_on宝石来做到这一点?

供参考,submission具有标签:

class Submission < ActiveRecord::Base
  searchkick

  acts_as_taggable_on :tags

1 个答案:

答案 0 :(得分:2)

您只需要将代码包装在Rails.cache.fetch中,

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