2
class Office < ActiveRecord::Base
    has_many :users

    searchable do
       text :name
       location :coordinates do
           Sunspot::Util::Coordinates.new(latitude, longitude) 
       end 
    end     
end

class User < ActiveRecord::Base
    belongs_to  :office

    searchable do
        text :name, :default_boost => 2
        text :description
    end
end

通过这种设置,我如何在 Rails 上使用 SunSpot(在 Solr 上)搜索给定纬度/经度内的用户?例如,我希望能够做到这一点:

  @search  = User.search() do
    fulltext(params[:q])
    with(:coordinates).near(@lat, @long, :precision => 5)
  end

以下工作正常:

  @search  = Office.search() do
    fulltext(params[:q])
    with(:coordinates).near(@lat, @long, :precision => 5)
  end

鉴于每个用户的纬度/经度确实存在于 Office 类中,实现此目的的最佳方法是什么?

4

1 回答 1

4

office关联应该在用户的可搜索块内。

鉴于此,这就是我要开始的内容(未经测试,在我的脑海中,等等):

class User < ActiveRecord::Base
  belongs_to  :office

  searchable do
    text :name, :default_boost => 2
    text :description
    location :coordinates do
      Sunspot::Util::Coordinates.new(office.latitude, office.longitude)
    end
  end
end

在这样的块中获取关联对象的值实际上是使用 Sunspot 处理非规范化的一种非常常见的模式。

于 2011-05-20T06:59:19.600 回答