【问题标题】:Searchkick / Rails working example with MongoidSearchkick / Rails 使用 Mongoid 的工作示例
【发布时间】:2014-04-22 17:08:19
【问题描述】:

我不知道如何正确挂钩视图/表单以使用 elasticsearch + mongoid 搜索我的文档。

我的 Searchkick 配置正在运行 - 我在 rails 控制台中获得了结果。但我不知道在控制器/模型/视图中按什么顺序放置东西以使其工作。从 rails 控制台我得到搜索结果,文档已正确映射,一切都很好。

我找不到使用 searchkick 的简单搜索表单的工作示例,其中包括模型、控制器和视图应该是什么样子的工作示例。

有人有工作示例来使用 Rails 4.1rc1 / Mongoid4 / Elasticsearch 1.0.1 结帐吗?

【问题讨论】:

    标签: ruby-on-rails elasticsearch mongoid


    【解决方案1】:

    我有 rails 4.0.2、Mongoid4 和 ElasticSearch >= 1

    无论如何,这在控制器中对我们有用:

    class CropSearchesController < ApplicationController
      def search
        query = params[:q].to_s
        @crops = Crop.search(query,
                             limit: 25,
                             partial: true,
                             misspellings: {distance: 2},
                             fields: ['name^20',
                                      'common_names^10',
                                      'binomial_name^10',
                                      'description'],
                             boost_by: [:guides_count]
                             )
        if query.empty?
          @crops = Crop.search('*', limit: 25, boost_by: [:guides_count])
        end
    
        # Use the crop results to look-up guides
        crop_ids = @crops.map { |crop| crop.id }
        @guides = Guide.search('*', where: {crop_id: crop_ids})
    
        render :show
      end
    end
    

    这是我们的模型:

    class Crop
      include Mongoid::Document
      include Mongoid::Timestamps
      include Mongoid::Slug
      searchkick
    
      field :guides_count, type: Fixnum, default: 0
    
      field :name
      field :common_names, type: Array
      validates_presence_of :name
      field :binomial_name
      field :description
      belongs_to :crop_data_source
      field :sun_requirements
      field :sowing_method
      field :spread, type: Integer
      field :row_spacing, type: Integer
      field :height, type: Integer
    
      embeds_many :pictures, cascade_callbacks: true, as: :photographic
      accepts_nested_attributes_for :pictures
    
      def search_data
        as_json only: [:name, :common_names, :binomial_name, :description, :guides_count]
      end
    
      slug :name
    end
    

    然后您就可以像往常一样访问视图中的@crops。

    您可以在 github 上查看我们的源代码:https://github.com/openfarmcc/OpenFarm

    (在寻找如何订购时偶然发现了这个问题,想通了,但我想我只是复制粘贴到这里以防万一有人觉得这很有用)。

    【讨论】:

    • 感谢分享!
    猜你喜欢
    • 2021-04-07
    • 2015-03-26
    • 1970-01-01
    • 2011-12-05
    • 2023-03-07
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    相关资源
    最近更新 更多