相关模型上的Mongoid 2d查询

时间:2015-12-09 09:47:06

标签: ruby-on-rails ruby mongodb mongoid geo

我有两个模型,LocationEvent

class Event
  include Mongoid::Document
  field :name, type: String
  belongs_to :location
  index({'location.coordinates' => '2d'}, {unique: true})  # I added this later on because I had an error when querying on location.coordinates
end

class Location
  include Mongoid::Document
  field :coordinates, type: Array
  index({coordinates: '2d'}, {unique: true})
  has_many :events
end

现在,如果我创建一个具有关联位置的Event

Location.create({coordinates: [40.7127837, -74.0059413]})
Event.create({name: "foo", location: Location.first})

如何查询特定位置附近的事件? 我试过这个:

Event.where('location.coordinates' => {'$near' => [40.7127837, -74.0059413], '$maxDistance' => 1000.fdiv(111.12)}).first

但是没有结果,而

Location.where('coordinates' => {'$near' => [40.7127837, -74.0059413], '$maxDistance' => 1000.fdiv(111.12)}).first

返回先前创建的Location对象。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

这看起来像是一个急切的加载问题。您是否尝试过.includes(:location)

Event.includes(:location).where('location.coordinates' => {'$near' => [40.7127837, -74.0059413], '$maxDistance' => 1000.fdiv(111.12)}).first

之前我曾与mongoid合作过,但如果需要的话似乎无法确定,以及它是哪个版本。某些版本的所有型号都默认启用了预先加载,并且需要设置配置文件标识映射中的旧版本,但这在第4版中已经消失。