2013-10-03 136 views
0

類別has_many的產品。關聯的搜索條件

在category_index我定義:
indexes :title
has products(:id), :as => :product_ids

在PRODUCT_INDEX我定義:
indexes :title

在搜索類:

product_ids = Product.search_for_ids('word', with: {user_id: 5}) 
categories = Category.search('word') 
categories_where_products_match = Category.search(with: {product_ids: products_ids}) 

如何合併categoriescategories_where_products_match合併爲一個ThinkingSphinx::Search對象?

+0

當你得到你的搜索時,你會得到一個散列嗎? – MZaragoza

+0

作爲搜索方法的結果,我得到了'ThinkingSphinx :: Search'。 – fantgeass

回答

1

對於您要在此處執行的操作,僅在產品上進行搜索時才起作用。您的分類索引可以有許多產品標題和許多產品用戶ID,但是沒有散列或字典的概念,因此Sphinx無法將兩個單獨的集合鏈接在一起。

像這樣的指數應該做的伎倆:

ThinkingSphinx::Index.define :product, with: :active_record do 
    indexes title 
    has user_id 
end 

然後搜索:

Product.search 'word', with: {user_id: 5} 

如果你想獲得此相匹配的類別,那麼我建議加入以下屬性到您的類別索引定義:

has products.id, as: :product_ids 

然後當搜索時:

product_ids = Product.search_for_ids 'word', with: {user_id: 5} 
categories = Category.search with: {product_ids: product_ids} 
+0

如果其他類別的字段符合搜索條件並且我也需要它們,我該怎麼辦?我不想使用「with」過濾結果。 – fantgeass

+0

我不明白 - 你想只包含特定用戶的產品結果嗎? – pat

+0

我編輯了這個問題。簡單地說,我想要的類別也符合「單詞」,不僅僅是產品的類別。 – fantgeass