Have to_json return a mongoid as a string

前端 未结 6 968
名媛妹妹
名媛妹妹 2020-12-09 19:00

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 retu

6条回答
  •  渐次进展
    2020-12-09 19:34

    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.

提交回复
热议问题