Rails: Sunspot text searching with model associations, using :through

旧时模样 提交于 2019-12-08 01:33:39

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/19628513/rails-sunspot-text-searching-with-model-associations-using-through

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!