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最大的优点之一。

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