首页 > 解决方案 > 子类 ActsAsTaggableOn:Tag?

问题描述

创建时尝试对ActsAsTaggableOn:Tag标签进行子类化。

module ActsAsTaggableOn
  class Tag < ::ActiveRecord::Base
    include AlgoliaSearch

    TAG_INDEX = "Tags_#{Rails.env}"

    algoliasearch per_environment: true do
      attribute :name, :taggings_count
      attributesToIndex ['name']
      customRanking ['desc(taggings_count)']
    end
  end
end

我正在尝试做的事情: 创建标签后,在 Algolia 中对其进行索引。

发生了什么: 保存标签或使用的模型acts_as_taggable_on(例如 Post)时,我收到此错误:

undefined method find_or_create_all_with_like_by_name

子类似乎ActsAsTaggableOn::Tag无法找到父find_or_create_all_with_like_by_name方法。

任何人都知道是否有办法继承 Tag 类?

标签: ruby-on-railsalgoliaacts-as-taggable-on

解决方案


当您可以创建一个模块并使用它来用这个新功能装饰现有类时,我会质疑您是否真的想将它子类化。

module MyTagDecorator
  def self.included(base)
    base.class_eval do
      include AlgoliaSearch
      TAG_INDEX = "Tags_#{Rails.env}"
      algoliasearch per_environment: true do
        attribute :name, :taggings_count
        attributesToIndex ['name']
        customRanking ['desc(taggings_count)']
      end
    end
  end
end

然后将模块包含在您要扩展的类中:

ActsAsTaggableOn::Tag.include(MyTagDecorator)

看:


推荐阅读