In trying to use the latest Sunspot code (from github) for geo search with Rails 3.0.0 , I was getting the following error while running Sunspot.index!(Location.all), where Location is my ActiveRecord class for storing locations:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NoMethodError: undefined method 'coordinates' for <Sunspot::DSL::Fields:...> |
After searching through the new code I found that coordinates is no longer a valid field type, but instead location is to be used. location expects an object that responds to lat and lng. Sunspot provides a handly little struct called Coordinates to be this object. So, here is my model code for setting up the search:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Location < ActiveRecord::Base | |
searchable do | |
location :coordinates | |
end | |
def coordinates | |
Sunspot::Util::Coordinates.new(self.lat,self.lng) | |
end | |
def coordinates=(sunspot_util_coordinates) | |
self.lat,self.lng = [sunspot_util_coordinates.lat, sunspot_util_coordinates.lng] | |
end | |
end |
notice the virtual attribute called coordinates which wraps the lat & lng ActiveRecord attributes. My search code now looks like this:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Location.search {with(:coordinates).near(42.331527,-83.075953)} |
And my search results are coming in as expected.