Thinking Sphinx, Rails, :has_many :through => ... has
Model: Product
has-many product-categories, :through => ...
Question 1) How do I index a many to many association with thinking sphinx
Must I use has?
Questions 2) How is this sea开发者_StackOverflow中文版rched in the controller
ex. Product.search params[:search-params], :conditions => {some_conditions}
I've not tried this on a has_many :through so shoot me down in flames if you have, but I don't see why this wouldn't work for you too, (I'm using it on a has_many association) you basically use your association in the index definition. Then searches against that model will also search the child records.
class Product < ActiveRecord::Base
has_many :product_categories
define_index do
indexes a_product_field_to_index
indexes product_categories.name, :as => :categories
end
end
In the controller:
@products = Product.search(params[:query] || '')
#params[:query] is simply the search string, I can't remember if you need to sanitize this, I would always assume you do unless you find out otherwise
In the view:
@products.each do |p|
p.categories.each do |cat|
end
end
If you don't already have it I would highly recommend the thinking-sphinx book available on peepcode: https://peepcode.com/products/thinking-sphinx-pdf
Hope that helps.
精彩评论