Question

How do I search with associations and through with sunspot?

class StaticController < ApplicationController

  def search
    @search = Sunspot.search Business, Service do
      fulltext params[:q]
      paginate :per_page => 10
      order_by_geodist(:location, *Geocoder.coordinates(params[:loc]))
    end
      @biz = @search.results

end

class Business < ActiveRecord::Base
  attr_accessible :name
  has_many :services, :through => :professionals

  searchable  do
    text :name #name in business column
    # how to do I get the services?
  end

end

class Service < ActiveRecord::Base
  attr_accessible :service
  belongs_to :professional
end

class Professional < ActiveRecord::Base
  belongs_to :business
  has_many :services, as: :servicable
end

In the view, I have this (lots of looping)

<%= @biz.each do |b| %>
  <%= b.name %>

  <!-- looping through professionals model -->
  <% b.professionals.each do |prof| %>

    <!-- looping through services model -->
    <% prof.services.each do |s| %>
      <%= s.service %>
    <% end %>

  <% end %>
<% end %>

This works if I search for a name that is within the business model, but what if I'm searching through a term that's in the Service model? It won't display correctly because my view is only coming from the business side. How do I make it so the business name will pop up if I search through Service model?

Thanks

Was it helpful?

Solution

You will need to make additional indexes for the associated models in the calling model to make this happen. For example:

class Business < ActiveRecord::Base
 attr_accessible :name
 has_many :services, :through => :professionals

 searchable  do
  text :name #name in business column
  text :services do  # this one for full text search
     services.map(&:service).compact.join(" ")
  end
  string :services , :multiple => true do #this one for exact searches
     services.map(&:service).compact
  end
 end
end 

After that you can do queries like:

Bussines.search do 
  with(:services, "some_service")
end.execute.results

Now you no longer have to do join on mysql tables to fetch data. You can just fetch data from the solr. This is one of biggest advantages of solr.

I hope this makes it clear. Fell free to drop a comment if you need more details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top