hasib32
hasib32

Reputation: 835

ember data createRecord without relationship fields data

I have a ember model like this:

var attr = DS.attr,
    hasMany = DS.hasMany,
    belongsTo = DS.belongsTo;
App.Message = DS.Model.extend({
    users: belongsTo('user'),
    message: attr(),
    user_id: attr(),
    inquiry_id: attr()
});

in my route i want to save it like this:

 var createMessage = this.store.createRecord('message', {
        'message': "this is sample message",
        'user_id': 1,
        'inquiry_id': 1
    });
createMessage.save();

But i saw in my request ember data also added users fields. I don't to send this field in my request. Is there any way I can do this. I want to use users relationship field only for get request not for post request. Version Ember: 1.6.1 and Ember-data: 1.0.0-beta.5

Upvotes: 0

Views: 343

Answers (2)

hasib32
hasib32

Reputation: 835

As @gorner suggested I modified my model like this:

var attr = DS.attr,
    hasMany = DS.hasMany,
    belongsTo = DS.belongsTo;
App.Message = DS.Model.extend({
    message: attr(),
    user: belongsTo('user'),
    inquiry: belongsTo('inquiry')
});

so, now I have single field to represent relationship. Also I am modifying

serializeBelongsTo method like this: 
    serializeBelongsTo: function(record, json, relationship){
        var key = relationship.key;
        var belongsTo = Ember.get(record, key);
        key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key;
        json[key+'_id'] = Ember.get(belongsTo, 'id'); //my backend support field name underscore
    }

Upvotes: 1

gorner
gorner

Reputation: 612

By default Ember Data will include any attributes you have defined on your model, regardless of whether or not they've been set to a value. If you need to remove an extra field from the request, you can create a custom serializer and override the serialize method to remove it from the default serialization:

App.MessageSerializer = DS.RESTSerializer.extend({
  serialize: function(message, options) {
    var json = this._super(message, options);
    delete json.users;
    return json;
  }
});

However, depending on the complexity of your app, things will probably go easier for you overall if you can stick to a single field to represent a relationship, rather than trying to manage two different fields for getting and setting the user(s). If you are able to access the desired User model and can set it to the user field, Ember can take care of the serialization to the correct field on submit.

Obviously it may need to be customized based on your server; as it appears your server is expecting it to be formatted user_id, I'm guessing you might want to look into Ember Data's ActiveModelSerializer class if you haven't already.

Upvotes: 1

Related Questions