我在我的应用程序中使用了Geocoder和Sunspot gem,并且我有一个名为的字段,该字段:search_near_address
假设让用户能够输入他们想要在其中搜索附近的地址X amount of miles
。我试图映射到的是我的商店:address
用于该:search_near_address
领域。这样,用户可以在:search_near_address
字段中输入地址(即 451 University Avenue, Palo Alto, CA ),它将在 50 英里的半径范围内进行搜索。
回答
太阳黑子 1.2.1
class Store < ActiveRecord::Base
attr_accessible :address, :latitude, :longitude
has_many :products
geocoded_by :address
after_validation :geocode
reverse_geocoded_by :latitude, :longitude
after_validation :reverse_geocode
end
class Product < ActiveRecord::Base
belongs_to :store
searchable do # Searching with product model.
string :search_near # For rake sunspot:reindex
location :location
end
def search_near_address
store.address if store # You may have to use the "if store".
end
def location
# may need the "if store" after longitude)....
Sunspot::Util::Coordinates.new(store.latitude, store.longitude)
end
end
class SearchController < ApplicationController
def index
@search = Product.search do |q| # Search with sunspot
q.fulltext params[:search]
q.with(:location).near(*Geocoder.coordinates(params[:search_near_address]), :precision => 4) if params[:search_near_address].present?
end
@products = @search.results # Return results from Product.search block.
end
end
# search/index/html.erb
<%= form_tag results_search_index_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search] %>
<%= text_field_tag :search_near_address, params[:search_near_address] %>
<%= submit_tag "Go", :name => nil %>
<% end %>