2

如何通过关联搜索和通过太阳黑子搜索?

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

在视图中,我有这个(很多循环)

<%= @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 %>

如果我搜索业务模型中的名称,这很有效,但如果我搜索Service模型中的术语怎么办?它不会正确显示,因为我的观点仅来自业务方面。Service如果我通过模型搜索,我该如何做才能弹出公司名称?

谢谢

4

1 回答 1

7

您需要为调用模型中的关联模型创建额外的索引才能实现这一点。例如:

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 

之后,您可以执行以下查询:

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

现在您不再需要加入 mysql 表来获取数据。您可以从 solr 中获取数据。这是 solr 的最大优势之一。

我希望这可以说清楚。如果您需要更多详细信息,请随时发表评论。

于 2013-10-28T07:07:03.343 回答