I'm using Rails 3.2 and Thinking Sphinx 3. I have the following associated models:
# country.rb
class Country < ActiveRecord::Base
has_many :states
end
# state.rb
class State < ActiveRecord::Base
belongs_to :country
has_many :state_shops
has_many :shops, :through => :state_shops
end
# state_shop.rb
class StateShop < ActiveRecord::Base
belongs_to :state
belongs_to :shop
end
# shop.rb
class Shop < ActiveRecord::Base
end
In country.rb
, I wanna search the name of shop
. Here is my index for country
:
# country_index.rb
ThinkingSphinx::Index.define :country, :with => :active_record do
indexes :name
has budget, duration, overall_rating, created_at
end
How should my associated index be in order to search the shop.name
?
You can pull in association columns in your index definitions pretty easily - here's an example for getting the shop names into the country index:
ThinkingSphinx::Index.define :country, :with => :active_record do
indexes name
indexes states.state_shops.shop.name, :as => :shop_names
has budget, duration, overall_rating, created_at
end
I've given the field an alias, so it doesn't conflict with the existing name
field (Sphinx will get confused otherwise).
A standard search will return any countries that match the country name or any of the associated shop names:
Country.search 'Australia'
But you can be a bit more specific if you're just looking for countries that match the query term to just any of the shop names:
Country.search :conditions => {:shop_names => 'Australia'}