2016-06-08 101 views
0

如何为searchkick实现类别过滤器。基本上我有一个输入字段接受查询字词,但我也想要一个下拉菜单,用户可以选择一个类别来搜索或搜索所有类别。有职位和类别Rails 4与多对多关系的searchkick

我的模型之间的许多一对多的关系是:

-- post.rb 
class Post < ActiveRecord::Base 
has_many :post_categories 
has_many :categories, through: :post_categories 
searchkick text_start: [:title] 
end 

-- category.rb 
class Category < ActiveRecord::Base 
    has_many :post_categories 
    has_many :posts, through: :post_categories 
end 

--post_category.rb 
class PostCategory < ActiveRecord::Base 
    belongs_to :post 
    belongs_to :category 
end 
我posts_controller index动作

现在,我有以下的,其通过返回匹配的所有帖子到目前为止作品查询参数,或者如果搜索输入中未提供查询参数,则返回所有帖子。

class PostsController < ApplicationController 

    def index 
     query = params[:q].presence || "*" 
     @posts = Post.search (query) 
    end 
end 

这个效果很好。但是我也希望在视图中添加一个类别过滤器,以便用户可以选择在特定类别内搜索查询字符串,或者在没有选择类别的情况下搜索所有类别。提前致谢。

+0

您是否尝试过增加一个类别筛选自己吗? –

回答

0

按照searchkick文档,您可以将参数添加到.search查询 - 请参阅here部分查询,具体位置。从文档样本:

​​

应SMT像

Post.search query, where: {category: [some_array]} 

注 - searchkick宝石转换从那里声明ElasticSearch过滤器(见here

更新条件 - 通过属性搜索的相关对象(不是模型本身),则应将其字段包含在search_index中 - 请参阅示例here

将类别标题添加到search_data方法。

class Project < ActiveRecord::Base 
    def search_data 
    attributes.merge(
     categories_title: categories.map(&:title) 
    ) 
    end 
end 

也对相关话题

通过searchkick默认search_data this问题是serializable_hash模型调用 - 见sources参考的回报。

def search_data 
    respond_to?(:to_hash) ? to_hash : serializable_hash 
end unless method_defined?(:search_data) 

其中不包括默认关联的任何东西,除非通过:包括参数 - source

def serializable_hash(options = nil) 
    ... 
    serializable_add_includes(options) do .. 
end 

def serializable_add_includes(options = {}) #:nodoc: 
    return unless includes = options[:include] 
... 
end 
+0

是的,我已经尝试过这种方法,但不会产生任何东西。我尝试过@posts = Post.search(query),其中:{category:[“Wedding”]}'但仍然没有结果。不知道我错过了什么。 – Alex

+0

为了以防万一,检查明显的语法错误 - 调用Post.search(查询,其中:{..})' - 里面的所有内容() –

+0

按照一般规则,避免在方法名称和括号之间留出空格 - write call params)而不是调用(params) - 你可以很容易地搜索这个,例如[here](http://stackoverflow.com/questions/7675093/spacing-around-parentheses-in-ruby) –