将mongoid对象作为json返回。

时间:2014-05-11 17:09:34

标签: ruby-on-rails ruby mongoid

我正在尝试用mongoid和rails构建一个api。 当我将对象作为json返回时,它部分工作但作为_id 返回一个哈希对象

render :json => @object

{"_id":{"$oid":"536faac8506574fb87000000"},"address":"Test address.","lat":0.0,"lon":0.0,"name":"Test Name"}

不应该返回“_id”:“536faac8506574fb87000000”

我该怎么做?

2 个答案:

答案 0 :(得分:3)

您只需在as_json方法中更改此行为:

module MyModel
  include Mongoid::Document

  def as_json(*args)
    res = super

    # convert BSON::ObjectId to string
    res["_id"] = res["_id"].to_s

    # or you also can change attribute name from _id to id
    # res["id"] = res.delete("_id").to_s

    res
  end
end

答案 1 :(得分:0)

实现此目的的一种方法是使用辅助函数,如下所示

 render :json => custom_json(@object)

 private
 def custom_json(value)
   result = value.map do |client|
     { :id => " #{client.id}",
       :address => client.address.to_s,
       :name => client.name.to_s
     }
   end
   result.to_json
 end