Rails:使用模型关联搜索太阳黑子文本,使用 :through [英] Rails: Sunspot text searching with model associations, using :through

查看:43
本文介绍了Rails:使用模型关联搜索太阳黑子文本,使用 :through的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

谢谢

推荐答案

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

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

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

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.

这篇关于Rails:使用模型关联搜索太阳黑子文本,使用 :through的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆