9

My ruby model, like so:

class User
  include Mongoid::Document
  field :first_name, type: String
  field :birthdate, type: Date

  validates :first_name, :birthdate, :presence => true

end

outputs an object like so:

{
_id: {
$oid: "522884c6c4b4ae5c76000001"
},
birthdate: null,
first_name: null,
}

My backbone project has no idea how to handle _id.$oid.

I found this article and code:

https://github.com/rails-api/active_model_serializers/pull/355/files

module Moped
  module BSON
    class ObjectId
      alias :to_json :to_s
    end
  end
end

I have no idea where to put this, and how to invoke it on the model output, so I tried inside:

/config/initializers/secret_token.rb

I'm new to Ruby and Rails and have no idea how to proceed, so any help is greatly appreciated

4

5 回答 5

33

Iterating on Kirk's answer:

In Mongoid 4 the Moped’s BSON implementation has been removed in favor of the MongoDB bson gem, so the correct version for Mongoid 4 users is:

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

    def as_json(*args)
      to_s.as_json
    end
  end
end
于 2013-12-28T09:46:20.123 回答
7

What you should do is place this in the initializer folder, create a file like this:

/config/initializers/mongoid.rb

module Moped
  module BSON
    class ObjectId
      alias :to_json :to_s
      alias :as_json :to_s
    end
  end
end
于 2013-09-06T01:10:12.030 回答
4

For guys using Mongoid 4+ use this,

module BSON
  class ObjectId
    alias :to_json :to_s
    alias :as_json :to_s
  end
end

Reference

于 2015-04-07T13:11:46.800 回答
3

Aurthur's answer worked for everything except rabl. If you are using rabl the attributes :id will throw an exception. The following code will be compatible with rabl.

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

      def as_json(*args)
        to_s.as_json
      end
    end
  end
end

For more information, see the github issue https://github.com/nesquena/rabl/issues/337

于 2013-10-02T23:03:30.763 回答
0

Here is a better answer

require "bson"

class Jbuilder < JbuilderProxy

  def _extract_method_values(object, *attributes)
    attributes.each do |key|
      value = object.public_send(key)

      if value.is_a? ::BSON::ObjectId
        value = value.to_s
      end

      _set_value key, value
    end
  end
end
于 2014-05-25T13:04:51.020 回答