Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

ruby on rails - Have to_json return a mongoid as a string

In my Rails API, I'd like a Mongo object to return as a JSON string with the Mongo UID as an "id" property rather than as an "_id" object.

I want my API to return the following JSON:

{
    "id": "536268a06d2d7019ba000000",
    "created_at": null,
}

Instead of:

{
    "_id": {
        "$oid": "536268a06d2d7019ba000000"
    },
    "created_at": null,
}

My model code is:

class Profile
  include Mongoid::Document
  field :name, type: String

  def to_json(options={})
    #what to do here?
    # options[:except] ||= :_id  #%w(_id)
    super(options)
  end
end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can monkey patch Moped::BSON::ObjectId:

module Moped
  module BSON
    class ObjectId   
      def to_json(*)
        to_s.to_json
      end
      def as_json(*)
        to_s.as_json
      end
    end
  end
end

to take care of the $oid stuff and then Mongoid::Document to convert _id to id:

module Mongoid
  module Document
    def serializable_hash(options = nil)
      h = super(options)
      h['id'] = h.delete('_id') if(h.has_key?('_id'))
      h
    end
  end
end

That will make all of your Mongoid objects behave sensibly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...