我如何使用Mongoid&amp ;;中的数组字段? Rails的?

时间:2012-01-09 20:41:15

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

我有一个有两个字段的地方模型:

class Place
  include Mongoid::Document

  field :name, :type => String
  field :loc, :type => Array

  index([[:loc, Mongo::GEO2D]], :background => true)

  validates_presence_of :name
end

我可以在我的视图中轻松输出lat和lon:

@place.loc['lat']

MongoDB中代表每个地方的记录如下所示:

{ "_id" : ObjectId( "0293uhjf2hfio2h3" ),
  "name" : "Starbucks",
  "loc" : {
    "lat" : 44.106667,
    "lon" : -73.935833
  }
}

我的问题是如何创建一个允许我编辑或创建新位置(纬度/经度)字段的表单?

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。我没有在地方模型中设置字段,而是创建了另一个名为“loc”的模型,并在其中添加了“embeds_one:loc”。所以地方模型现在看起来像这样:

class Place
  include Mongoid::Document
  field :name

  index([[:loc, Mongo::GEO2D]], :background => true)

  embeds_one :loc
  validates_presence_of :name
end

loc模型现在看起来像这样:

class Loc
  include Mongoid::Document

  field :lat, :type => Integer
  field :lon, :type => Integer

  embedded_in :place
end

所以,现在我可以在我的表单中输入输入字段:

<input type="text" name="place[loc][lat]" id="place_loc_lat">