简体   繁体   中英

thinking_sphinx returns an array

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM