Zach Shallbetter
Zach Shallbetter

Reputation: 1911

Exclude model properties when saving with Ember-Data

I have a model that has an image property. When saving images I would like to not Post that property to the endpoint. I was thinking perhaps I could .set the changes on everything beside the image property then save. But save still posts everything.

Also, my Adapter supports PATCH so I can successfully save portions of the model.

My model

App.Photo = DS.Model.extend({
  title: attr(),
  description: attr(),
  image: attr(),
  authors: hasMany('author'),
  imageURL: function() {
    return document.location.origin + '/media/' + this.get('image');
  }.property('image'),
  created: attr('date')
});

My Controller

App.PhotoController = Ember.ArrayController.extend({
  actions: {
    save: function() {
      this.get('model').save().then(function(success) {
        self.transitionToRoute('photos').then(function() {
        });
      });
    }
  }
});

Upvotes: 4

Views: 2445

Answers (2)

webpapaya
webpapaya

Reputation: 809

I think since this PR on Ember there is a better way to handle the exclusion of an attribute.

import DS from 'ember-data';

export default DS.JSONSerializer.extend({
  attrs: {
    image: {serialize: false}
  }
});

If you have more than one attribute to exclude the above code looks cleaner. Also have a look on the documentation of DS.JSONSerializer

Upvotes: 15

Steve H.
Steve H.

Reputation: 6947

You can override the serializeAttribute function on the Serializer:

App.PhotoSerializer = DS.DjangoRESTSerializer.extend({
    serializeAttribute: function(record, json, key, attribute) {
        if (attribute.name !== 'image') {
            this._super(record, json, key, attribute);
        }
    }
});

Upvotes: 4

Related Questions