【发布时间】:2013-11-21 00:19:26
【问题描述】:
我很难理解如何做到这一点,而且似乎有很多人问这个问题而没有答案。我有一个带有邮政编码的用户表。我创建了一个 zips 表,其中包含美国的每个带有纬度/经度的邮政编码。
我想做的是将两者连接起来,以便用户可以搜索其他用户。我有 Thinking Sphinx,我更愿意继续使用它。我想为用户提供一个用于搜索距离的复选框(5、10、25、50、100、500 英里)。结果应始终返回最近的用户。
我认为这不需要来自控制器或模型的代码,但是如果需要,请询问,我会提供。
搜索表格:
<%= form_tag searches_path, method: :get do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= button_tag "Search", name: nil %>
</p>
<% end %>
<P><%= link_to "Advanced Search", new_search_path %><p>
<%= form_tag users_path, method: :get do %>
<%= label :zip_code, "Enter zip code: " %>
<%= text_field_tag :zip_code, params[:zip_code] %>
<% end %>
/indices/user_index.rb:
ThinkingSphinx::Index.define :user, :with => :active_record do
# fields
indexes name, :as => :user, :sortable => true
indexes religion, zip_code, about_me, career, sexuality, children, user_smoke, user_drink, gender, ethnicity, education
# attributes
has id, created_at, updated_at
has zips.city, :as => :zip_city
has "RADIANS(zips.lat)", :as => :latitude, :type => :float
has "RADIANS(zips.lon)", :as => :longitude, :type => :float
end
用户模型:
has_and_belongs_to_many :zips
邮编型号:
class Zip < ActiveRecord::Base
attr_accessible :city, :lat, :lon, :code, :zipcode
has_and_belongs_to_many :users
validates :code, uniqueness: true
self.primary_key = 'code'
def self.code(code)
find_by(:code => code)
end
end
用户表有以下列:zip_code。
邮政编码表包含以下列:code、city、state、lat、lon
【问题讨论】:
-
我一开始就卡住了。所以我有索引文件设置。如您所见,它是从 User 表中提取的。我是否应该创建另一个名为 zip_index.rb 的 zips 表,该表包含美国所有带 lat/lon 的邮政编码?在用户模型中我需要做什么样的工作(或者我需要创建一个搜索模型)。有很多关于 Sphinx 的信息,我已经为应用程序的其他部分设置了它。只是没有关于地理搜索方面的信息。
-
我认为你需要实现Haversive formula,除非 Thinking Sphinx 有一个功能可以为你做这件事。该公式计算球体上两点之间的距离。该函数只是一些基本的触发;它的 MySQL 版本是
(6378.10 * ACOS(COS(RADIANS(lat1)) * COS(RADIANS(lat2)) * COS(RADIANS(long1) - RADIANS(long2)) + SIN(RADIANS(lat1)) * SIN(RADIANS(lat2)))) -
解决了吗?那是
locations上的User模型?
标签: mysql ruby-on-rails thinking-sphinx zipcode