Search code examples
ember.jsember-datajsonapi-resources

How to prevent Ember Data from saving attribute (ie., Read-only attribute)


I am creating an online form builder using Ember 2.0 on the front-end and Rails 4.2 on the back-end with the json_api_resources gem.

In the process of publishing a form, a user must be able to cut/paste a snippet of code into his/her webpage in order to 'ajax in' the form they have configured.

Thus the 'embed-snippet' attribute of the Form model should be read-only. I do not want the contents of the snippet field to be sent back to the server when the user makes a change to the form and re-saves the record.

Some approaches I have considered:

  • Modifying the serializer to check for this specific attribute and drop it from the payload before sending it to the back-end
  • Converting the 'embed-snippet' field to a separate model with a relationship to the Form model, and then excluding it somehow from the save
  • Creating a new Ember Data attribute type

Ideally there would be a better way to deal with this problem.

Something like:

'DS.attr('string', { readOnly: true })

So my question is, what is the best way to ensure the content of this field does not get sent back to the server?


Solution

  • To get the { readOnly: true } functionality (which makes it easier to add new models/attrs) you can customize the serializeAttribute method on the JSONAPISerializer:

    (in serializers/application.js):

    import DS from 'ember-data';
    
    export default DS.JSONAPISerializer.extend({
      serializeAttribute(snapshot, json, key, attribute) {
        // do not serialize the attribute!
        if (attribute.options && attribute.options.readOnly) {
          return;
        }
        this._super(...arguments);
      },
    });