Rails 4 searchkick与多对多关系

时间:2016-06-08 21:34:40

标签: ruby-on-rails ruby-on-rails-4.2 searchkick

如何为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索引操作中,我有以下内容,它通过返回与查询参数匹配的所有帖子到目前为止工作,或者如果搜索输入中没有提供查询参数,则返回所有帖子。

class PostsController < ApplicationController

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

到目前为止效果很好。但我还想在视图中添加类别过滤器,以便用户可以选择搜索特定类别中的查询字符串,或者如果未选择任何类别则搜索所有类别。提前谢谢。

1 个答案:

答案 0 :(得分:1)

根据searchkick文档,您可以向.search查询添加参数 - 请参阅here部分查询,特别是在哪里。来自docs的示例:

Product.search "apples", where: {in_stock: true}, limit: 10, offset: 50

应该像smt一样

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

注意 - searchkick gem将where语句中的条件转换为ElasticSearch过滤器(参见here

更新 - 要按相关对象(不是模型本身)的属性进行搜索,您应该将其字段包含在search_index中 - 请参阅示例here

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

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

同样this相关主题的问题

默认情况下,searchkick的search_data返回serializable_hash模型调用-see sources以供参考。

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

默认情况下不包含任何关联,除非传递给:include parameter - source

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

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