Reputation: 701
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
With this kind of a setup, how can I search using SunSpot (on Solr) on Rails for a user within a given lat/long? For example, I want to be able to do this:
@search = User.search() do
fulltext(params[:q])
with(:coordinates).near(@lat, @long, :precision => 5)
end
The following works just fine:
@search = Office.search() do
fulltext(params[:q])
with(:coordinates).near(@lat, @long, :precision => 5)
end
What is the best way to accomplish this given that the lat/long for each User really lives in the Office class?
Upvotes: 2
Views: 695
Reputation: 7944
The office
association should be in scope inside your User's searchable block.
Given that, here's what I would start with (untested, off the top of my head, etc):
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
Fetching values for associated objects in a block like this is actually a pretty common pattern for handling denormalization with Sunspot.
Upvotes: 4