I've struggled with this for a couple of hours today so in the hope it answers someone else's question, here's how I got the distance attribute when using the Geokit gem + plugin on an acts_as_mappable :through model class.
The model -
class Client < User
has_one :address, :as => :addressable, :dependent => :destroy
...
end
The search action in the controller -
def search
origin = params[:use_my_location] ? current_user.address.inline : params[:origin]
bounds = Geokit::Bounds.from_point_and_radius(origin , params[:within])
@clients = Client.find(:all, :bounds => bounds, :conditions => ['state = ?','active'])
@clients.sort_by_distance_from(origin)
end
and in ApplicationController (could just as well be in the above controller) -
module Geokit
module Mappable
def to_lat_lng
return self if instance_of?(Geokit::LatLng) || instance_of?(Geokit::GeoLoc)
return LatLng.new(self.address.send(self.address.class.lat_column_name),
self.address.send(self.address.class.lng_column_name)) if self.class.respond_to?(:acts_as_mappable)
nil
end
end
end
so that's monkey-patched (I think) the Geokit Mappable module to lookup an address association when sorting by distance. Ideally this code should look up the :through part of the association instead of hardwiring the association name. The distance attribute is populated by the sort and <model>.distance is available in the view.