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