如何使用acts_as_taggable_on缓存标记?

Vol*_*ldy 6 caching ruby-on-rails acts-as-taggable-on

我有标签上下文的模型:

class Product < ActiveRecord::Base
  acts_as_taggable_on :categories
end
Run Code Online (Sandbox Code Playgroud)

我正在尝试初始化标签缓存:

class AddCachedCategoryListToProducts < ActiveRecord::Migration
  def self.up
    add_column :products,  :cached_category_list, :string
    Product.reset_column_information
    products = Product.all
    products.each { |p| p.save_cached_tag_list }
  end
end
Run Code Online (Sandbox Code Playgroud)

但是cached_category_list没有初始化.我做错了什么?有没有人可以使用这个gem的缓存(我的版本是2.0.6)?

ms-*_*ati 15

好吧,今天我遇到了同样的问题.我终于解决了它,我的迁移缓存了所需的标签.您的迁移问题有两个方面:

  1. 设置缓存的ActsAsTaggable代码需要在重置列信息后再次运行.否则,不会创建缓存方法(请参阅https://github.com/mbleigh/acts-as-taggable-on/blob/v2.0.6/lib/acts_as_taggable_on/acts_as_taggable_on/cache.rb)

  2. 您调用的方法save_cached_tag_list不会自动保存记录,因为它是作为before_save挂钩安装的,并且它不希望创建无限循环.所以你必须打电话给保存.

因此,尝试使用以下内容替换您的迁移,它应该工作:

class AddCachedCategoryListToProducts < ActiveRecord::Migration
  def self.up
    add_column :products,  :cached_category_list, :string
    Product.reset_column_information
    # next line makes ActsAsTaggableOn see the new column and create cache methods
    ActsAsTaggableOn::Taggable::Cache.included(Product)
    Product.find_each(:batch_size => 1000) do |p|
      p.category_list # it seems you need to do this first to generate the list
      p.save! # you were missing the save line!
    end    
  end
end
Run Code Online (Sandbox Code Playgroud)

应该这样做.


小智 -5

如果您将其与自有标签结合使用,这可能就是问题所在。查看gem的代码,似乎不支持拥有标签的缓存

希望这可以帮助,

贝斯特,J