Have to_json return a mongoid as a string

前端 未结 6 959
名媛妹妹
名媛妹妹 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条回答
  •  -上瘾入骨i
    2020-12-09 19:46

    You can change data in as_json method, while data is hash:

    class Profile
      include Mongoid::Document
      field :name, type: String
    
       def as_json(*args)
        res = super
        res["id"] = res.delete("_id").to_s
        res
      end
    end
    
    p = Profile.new
    p.to_json
    

    result:

    {
        "id": "536268a06d2d7019ba000000",
        ...
    }
    

提交回复
热议问题