1

我有一个由地理位置查询返回的 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
4

1 回答 1

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 }
于 2012-08-14T12:26:35.623 回答