使用geoNear和Rails / Mongoid

时间:2012-11-08 13:21:13

标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid geospatial

我在使用MongoDB / Rails查询地理空间索引时遇到问题。 我正在使用这个宝石 - https://github.com/kristianmandrup/mongoid_geospatial

这是我相当基本的模型:

class Company
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Geospatial

  field :name, type: String

  field :location, type: Array, spatial: true

  spatial_index :location

  validates :location, location: true
end

然后,在我的控制器中,我有这个

    #@vendors = Vendor.where(:location.near => {:point => [-2.1294761000000335,57.0507625], :max => 5})

然而,这并没有返回预期的结果(即它从整个地方返回的东西,而不仅仅是那个特定的lon / lat附近)

另外,我怎么用这个做geoNear?
这样我可以从每个结果的中心点返回距离吗?

注意 在写完这个问题之后,我看到宝石已经更新,但我不确定是否有更好的选择......?

1 个答案:

答案 0 :(得分:4)

您不需要mongoid_geospatial gem来执行geoNear查询:mongoid already supports it(至少在版本3中)。

将您的模型更改为:

class Company
  include Mongoid::Document
  include Mongoid::Timestamps

  field :name, type: String

  field :location, type: Array

  index({location: "2d"})

  validates :location, location: true
end

将您的查询运行为:

@vendors = Vendor.geo_near([-2.1294761000000335,57.0507625]).max_distance(5)