我有一个由地理位置查询返回的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
我发现this post与同一类错误相关,但经过验证的答案对我不起作用。
有什么想法吗?
修改
以下是我发生问题的模型:
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
答案 0 :(得分:0)
目前我已通过降级我的宝石解决了这个问题,如下所示:
gem 'mongo', '1.4.0'
gem "mongoid", "~> 2.4"
gem "bson_ext", "~> 1.5"
仍有可能使用以下hack,但它会阻止您自己格式化模型中的json输出。
format.json { render json: Hash.from_xml(@data.to_xml).to_json, :status => 200 }