Last active
May 17, 2024 03:33
-
-
Save raykao/d87af8b41c2bf939b423 to your computer and use it in GitHub Desktop.
Rails + Mongoid _id attribute to id and string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/initializers/mongoid.rb | |
# convert object key "_id" to "id" and remove "_id" from displayed attributes on mongoid documents when represented as JSON | |
module Mongoid | |
module Document | |
def as_json(options={}) | |
attrs = super(options) | |
id = {id: attrs["_id"].to_s} | |
attrs.delete("_id") | |
id.merge(attrs) | |
end | |
end | |
end | |
# converts object ids from BSON type object id to plain old string | |
module BSON | |
class ObjectId | |
alias :to_json :to_s | |
alias :as_json :to_s | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to set this up?