尽管包含在内,但关注模块在模型中不可用(NoMethodError)

Concern module not available in model despite being included (NoMethodError)

我正在将我的应用程序从 solr 迁移到 Elasticsearch 以进行文档搜索。部署 Elasticsearch 的推荐模式是在 Rails 关注点中包含 Elasticsearch 功能(即 Elasticsearch::ModelElasticsearch::Model::Indexing),然后将此模块包含在您的模型中。我已经这样实现了。 (在我处理这个过程中,一些方法暂时被注释掉了。)

#app/models/concerns/elasticsearch_user.rb
require 'active_support/concern'

module ElasticsearchUser

extend ActiveSupport::Concern

included do
  require 'elasticsearch/model'
  include Elasticsearch::Model
  include Elasticsearch::Model::Indexing

  #mapping do
  #  #to-do
  #end

  #def self.search(query)
  #  _elasticsearch_.search(
  #    {
  #        query: {
  #         multi_match: {
  #             query: query,
  #             fields: ['username^2', 'email', 'full_name']
  #         }
  #        }
  #    }
  #  )
  #end

  end
end


#User.rb
...
# Elasticsearch configuration
include ElasticsearchUser
# index_name "users" <-- This value is inferred automatically by the model name
settings index: { number_of_shards: 1 } do
  mappings dynamic: 'false' do
    indexes :username
    indexes :email
    indexes :full_name
  end
end
...
def as_indexed_json(options={})
  self.as_json(only: [:username, :email, :full_name],
               methods: [:full_name]
  )
end

我可以毫无问题地调用 Model.importModel.search。调用 Model._elasticsearch_.create_index! 之类的东西(有和没有 _elasticsearch_ 命名空间)会抛出 NoMethodError。我试过直接在我的模型定义中包含 Elasticsearch::Model 但没有成功。我也试过在我的模型的顶部要求'active_support/concern' - 也没有运气。 module/concern 显然没有包含在我的模型中,但我不知道为什么。

您使用的 rails 版本是否正确 尝试!!在控制台中

require 'active_support/concern'

如果 returns nil 模块没有被导入

这其实跟包括顾虑无关。我在我的搜索方法中添加了一些日志记录 (we made it to the search),并在控制台输出中找到了它。在 Elasticsearch 人员的帮助下,我们意识到我使用的是 _elasticsearch_,但它是带有两个下划线的 __elasticsearch__。在所有事情中...