首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongoid搜索/ Rails工作示例

Mongoid搜索/ Rails工作示例
EN

Stack Overflow用户
提问于 2014-03-17 13:16:13
回答 1查看 1.1K关注 0票数 0

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

我的Search腿配置正在工作,- I在rails控制台中获取结果。但是,我不知道在控制器/模型/视图中将事情按什么顺序放置以使其工作。从rails控制台我得到搜索结果,文档被正确地映射,一切都很好。

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

有人用Rails 4.1rc1 / Mongoid4 /ElasticSearch1.0.1签出一个工作示例吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-18 04:40:56

我有rails 4.0.2,Mongoid4和ElasticSearch >= 1

不管怎么说,这对我们在控制器中是有效的:

代码语言:javascript
复制
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

这就是我们的模式:

代码语言:javascript
复制
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

然后你就会像平常一样进入视野中的庄稼。

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

(只是在寻找如何进行排序时偶然发现了这个问题,想出了办法,但我想我应该把这个粘贴在这里,以防有人发现这个有用)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22455312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档