当使用带有acts_as_mappable:to的Geokit时,'distance'字段会被删除

时间:2011-05-15 06:44:36

标签: ruby-on-rails geokit

我们知道当使用带有acts_as_mappable的Rails中的Geokit gem时,距离字段会被删除:通过模型类。我想知道是否有办法解决这个问题,以恢复距离场。我试着在这里遵循猴子修补示例: http://www.sobyteme.com/news/2010/05/13/computers/2010/06/25/geokit-acts_as_mappable-through-with-distance-attribute/ 但它对我不起作用。

1 个答案:

答案 0 :(得分:1)

好吧,史蒂夫在他的网站上提出的建议是准确的,我在找完之后错过了调用 sort_by_distance_from 。所以这个答案可归功于他。

我在Rails v3.0.7上。这是我的代码:

class Office < ActiveRecord::Base
    has_many :users
    acts_as_mappable :default_units => :miles, 
                     :default_formula => :sphere, 
                     :lat_column_name => :latitude,
                     :lng_column_name => :longitude
end

class User < ActiveRecord::Base
    belongs_to  :office
    acts_as_mappable :through => :office
end

users_controller.rb:

# Monkey patching to include the 'distance' attribute
module Geokit
  module Mappable
    def to_lat_lng
      return self if instance_of?(Geokit::LatLng) || instance_of?(Geokit::GeoLoc)
      return LatLng.new(self.office.send(self.office.class.lat_column_name),
        self.office.send(self.office.class.lng_column_name)) if self.class.respond_to?(:acts_as_mappable)
      nil
    end
  end 
end

class UsersController < ApplicationController

  def location
    @lat = params[:lat].to_f
    @long = params[:long].to_f
    @origin = [@lat, @long]
    @users = User.find(:all, 
         :origin => @origin,
         :conditions => "distance < 3")

    # We have to add this to get the 'distance' field
    @users.sort_by_distance_from(@origin)

    respond_to do |format|
      format.html
      format.xml  { render :xml => @users.to_xml(:methods => :distance)}
      format.json  { render :json => @users.to_json(:methods => :distance)}
    end
  end 
...
end