2

使用模型關聯搜索太陽黑子文本如何使用關聯進行搜索並通過太陽黑子進行搜索?Rails:使用:通過

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型號搜索,我該如何做到這樣企業名稱會彈出?

感謝

回答

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最大的優點之一。

我希望這說清楚。如果您需要更多詳細信息,請隨時留下評論。