fantgeass
fantgeass

Reputation: 35

Search condition for association

Category has_many products.

In category_index I defined:
indexes :title
has products(:id), :as => :product_ids

In product_index I defined:
indexes :title

In searcher class:

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})

How can I merge categories and categories_where_products_match into one ThinkingSphinx::Search object?

Upvotes: 0

Views: 81

Answers (1)

pat
pat

Reputation: 16226

For what you're trying to do here, it's only going to work when searching on Product. Your Category index can have many product titles, and many product user ids, but there's no concept of hashes or dictionaries, so there's no way for Sphinx to link the two separate collections together.

An index like this should do the trick:

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

And then searching:

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

If you wanted to get the categories that match this, then I'd recommend adding the following attribute to your Category index definition:

has products.id, as: :product_ids

And then when searching:

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

Upvotes: 1

Related Questions