How can I get collection of attributes for search result?

I.E.

I search through Product model which have many Category:

class Product < ActiveRecord::Base
  has_many :categories

Here is my index:

ThinkingSphinx::Index.define :product, with: :active_record do
  ###
  has category(:id), as: :direct_category_id

So, I search through query

products = Product.search params[:query]
categories = Category.find(products.map(&:category_id)) # slow & bad & ugly

But this method is so slow and bad. Is there any way to get all atttributes from search results instead collect?

有帮助吗?

解决方案 2

okay. I solved by myself. The solution use facets

First of all, we need to add direct_category_id:

has category(:id), as: :direct_category_id, facet: true

After that, we need just to use

category_ids = products.facets[:direct_category_id].keys
categories = Category.where(id: category_ids)

其他提示

search       = Product.search params[:query]
search.context[:panes] << ThinkingSphinx::Panes::AttributesPane
category_ids = search.collect { |product|
  product.sphinx_attributes['direct_category_id']
}
categories   = Category.find category_ids

However, keep in mind that if you run this in the console the first line evaluates the search request because IRB renders the result. This means the pane can't be added... so you'll want to add ; '' or similar at the end of the first line (again: only necessary in a Rails console):

search       = Product.search params[:query]; ''
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top