我有一个由地理位置查询返回的 Mongo 对象数组,例如:
@data = Record.geo_near([lng,lat], :max_distance => dist, :unit => :m, :spherical => true)
然后我尝试根据预期的格式序列化响应:
respond_to do |format|
format.html
format.json { render json: @data, :status => 200 } # Not working
format.xml { render xml: @data, :status => 200 } # Working !
end
奇怪的是,XML 一切顺利,但 JSON 出现此错误:
ActiveSupport::JSON::Encoding::CircularReferenceError in BouncesController#populars
object references itself
我发现这篇文章与相同类型的错误有关,但经过验证的答案对我不起作用。
有任何想法吗?
编辑
这是发生问题的模型:
class MyModel
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Spacial::Document
spacial_index :loc, :min => -180, :max => 180
belongs_to :user
field :text, :type => String
field :loc, :type => Array, spacial: true
field :accuracy, :type => Float
def as_json(options={})
{
"id" => self.id,
"text" => self.text,
"loc" => self.loc,
"accuracy" => self.accuracy,
"user" => {
"id" => self.user['_id'],
"login" => self.user['login'],
"role" => self.user['role']
},
"created_at" => self.created_at,
"updated_at" => self.updated_at
}
end
end