Skip to content

Instantly share code, notes, and snippets.

@raykao
Last active May 17, 2024 03:33
Show Gist options
  • Save raykao/d87af8b41c2bf939b423 to your computer and use it in GitHub Desktop.
Save raykao/d87af8b41c2bf939b423 to your computer and use it in GitHub Desktop.
Rails + Mongoid _id attribute to id and string
# 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
@JenuelDev
Copy link

how to set this up?

@stevenfreemann
Copy link

thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment