Ember-data and MongoDB, how to handle _id

后端 未结 9 1952
眼角桃花
眼角桃花 2021-02-08 17:15

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

相关标签:
9条回答
  • 2021-02-08 17:34

    The second part of joscas's answer fixed the id issue for me with Rails4/Ruby2 except I had to .to_s the _id.

    class UserSerializer < ActiveModel::Serializer
      attributes :id, :name, :email
      def id
        object._id.to_s
      end
    end
    
    0 讨论(0)
  • 2021-02-08 17:35

    I don't know exactly when this was added, but you can just tell Ember-Data that the primaryKey is _id:

    DS.RESTAdapter.extend({
      serializer: DS.RESTSerializer.extend({
        primaryKey: '_id'
      })
    });
    
    0 讨论(0)
  • 2021-02-08 17:36

    Ahh, instead of including _id in your JSON, you could craft the JSON to instead use the id method rather than the _id attribute. Ways:

    You could use rabl, and the JSON could be like:

    object @user 
    attributes :id, :email
    node(:full_name) {|user| "#{user.first_name} #{user.last_name}"}
    

    You could also craft the as_json method

    class User
      def as_json(args={})
        super args.merge(:only => [:email], :methods => [:id, :full_name])
      end
    end
    
    0 讨论(0)
  • 2021-02-08 17:39

    I had a similar problem using ember.js with ember-resource and couchdb, which also stores it's IDs as _id.

    As solution to this problem I defined a superclass for all my model classes containing a computed property to duplicate _id into id like this:

    // get over the fact that couchdb uses _id, ember-resource uses id
    id: function(key, value) {
        // map _id (couchdb) to id (ember)
        if (arguments.length === 1) {
            return this.get('_id');
        }
        else {
            this.set('_id', value);
            return value;
        }
    }.property('_id').cacheable()
    

    Maybe this could solve your problem too?

    0 讨论(0)
  • 2021-02-08 17:48

    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

    0 讨论(0)
  • 2021-02-08 17:49

    If you use Mongoid3, here is the monkey patch may work for you.

    https://gist.github.com/4700909

    0 讨论(0)
提交回复
热议问题