2016-06-08 69 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) –