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 for ID so I tried to override it like this:
App.User = DS.Model.extend
primaryKey: "_id"
name: DS.attr "string"
image: DS.attr "string"
This seems to work most of the time but in some instances I get exceptions from ember saying:
Uncaught Error: assertion failed: Your server returned a hash with the key _id but you have no mappings
I suspect this might be a bug in ember-data because it's still heavily under development, but I was trying to find a way to get to map _id to id on the server side in rails? I'm using mongoid to do the mongo mapping.
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 :)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 serializerAdd the following Rails initializer
Mongoid 3.x
Mongoid 4
Active Model Serializer for
Building
Resulting JSON
This is a monkey patch suggested by brentkirby and updated for Mongoid 4 by arthurnn
The second part of joscas's answer fixed the id issue for me with Rails4/Ruby2 except I had to .to_s the _id.
I don't know exactly when this was added, but you can just tell Ember-Data that the primaryKey is _id:
Although the question is quite old but i still think my answer could help others:
If you are using ActiveModelSerializer then you just need to do this :
It works all fine. I am using emberjs on the front end btw.
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):And then include your serializer. Something like that:
This fixes the
_id
problem