I\'m using ember-data with rails and MongoDB and am having problem with the way IDs are stored in MongoDB - in a _id field.
Ember-data will use id as the default field f
If you are using Mongoid here is a solution that makes it so you don't have to add a method def id; object._id.to_s; end
to every serializer
Add the following Rails initializer
Mongoid 3.x
module Moped
module BSON
class ObjectId
alias :to_json :to_s
alias :as_json :to_s
end
end
end
Mongoid 4
module BSON
class ObjectId
alias :to_json :to_s
alias :as_json :to_s
end
end
Active Model Serializer for Building
class BuildingSerializer < ActiveModel::Serializer
attributes :id, :name
end
Resulting JSON
{
"buildings": [
{"id":"5338f70741727450f8000000","name":"City Hall"},
{"id":"5338f70741727450f8010000","name":"Firestation"}
]
}
This is a monkey patch suggested by brentkirby and updated for Mongoid 4 by arthurnn
The best way is to use ActiveModel::Serializers. Since we are using Mongoid, you will need to add an include statement like that (see this gist from benedikt):
# config/initializers/active_model_serializers.rb
Mongoid::Document.send(:include, ActiveModel::SerializerSupport)
Mongoid::Criteria.delegate(:active_model_serializer, :to => :to_a)
And then include your serializer. Something like that:
# app/serializers/user_serializer.rb
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :email
def id
object._id
end
end
This fixes the _id
problem
An other way could be to use (if possible for you) the ActiveModel::Serializer. (I think it should be close to rabl (?))
From the ember-data gihtub: https://github.com/emberjs/data:
Out of the box support for Rails apps that follow the active_model_serializers gem's conventions
When we began with ember-data we were crafting as_json()
, but using the gem is definitely better :)