Question

I have a controller with a results of the search, based on thinking-sphinx. Both find_kind_cd and find_category_ids are sphinx scopes.

@products.search return an array. I need something like ActiveRecord::Relation or something like that, because I want to implement some methods to it, like includes or maximum. How can I implement this methods with array?

@products = Product.find_kind_cd(Product.product)

@category = Category.find_by(id: params[:category])
@products = @products.find_category_ids(@category.subtree_ids) if @category

@products = @products.search(params[:query]) if params[:query].present?
# TODO includes - bullet gem

@products = @products.page(params[:page]).per(params[:per] || 12)
Was it helpful?

Solution

Search results cannot be an ActiveRecord::Relation, because you're querying against Sphinx, not a database. What you actually get back is not an array, but an instance of ThinkingSphinx::Search which behaves very similarly to an array.

However, search calls are lazily evaluated, and page and per are methods that are available on ThinkingSphinx::Search, so you can use those. As for includes, you'll need to do the following instead:

@products = @products.search(:sql => {:include => :category})

There's nothing like maximum though. But if you do want an aggregation from the database based on Sphinx search results, this should do the trick:

Product.where(id: Product.search_for_ids(params[:query]).to_a).maximum(:cost)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top