4
votes

I am using Rails 4, Ember 1.2.0 and Ember Data 1.0.0-beta.3 and DS.ActiveModelSerializer.

I have trouble saving a new record with a 'has many' relationship. Two model records should be created but only by one POST request.

I have 2 models which looks like this:

Lingohub.SupportCase = DS.Model.extend({
  subject: DS.attr('string'),
  status: DS.attr('string'),
  created_at: DS.attr('date'),

  supportCaseMessages: DS.hasMany('supportCaseMessage')
});

Lingohub.SupportCaseMessage = DS.Model.extend({
  supportCase: DS.belongsTo('supportCase'),
  text: DS.attr('string'),
  created_at: DS.attr('date')
});

My NEW route creates support case and support case massage:

Lingohub.SupportCasesNewRoute = Ember.Route.extend({
  model: function() {
    var support_case = this.store.createRecord('supportCase');
    support_case.get('supportCaseMessages').createRecord();
    return support_case;
  }
});

My new form looks like this: (I don't know if you can bind an child attribute easier?)

<form {{action 'create' this on="submit"}} id="new_support_case">

  {{input value=subject}}

  {{!-- {{supportCaseMessages.0.text}} --}}
  {{#each supportCaseMessages}}
    {{textarea value=text}}
  {{/each}}

  <input type="submit">

</form>

'create' action in the controller:

Lingohub.SupportCasesNewController = Ember.ObjectController.extend({

  actions: {
    create: function(supportCase) {
      var message = supportCase.get('supportCaseMessages.content')[0];

      console.log(message.get('text'))

      supportCase.save();

    }
  }

});

The POST Request to the Server only sends the 'support case'!!

{"support_case"=>{"subject"=>"aaaaaa", "status"=>nil, "created_at"=>nil}}

How can I send the additional record 'support case message' and the relationship ?

1

1 Answers

0
votes

I try to answer my own question. If I do the following I get "support_case_messages" embedded in "support_case", is this really the best way to send 'two models' in one POST request?

Lingohub.SupportCaseSerializer = DS.ActiveModelSerializer.extend({
  serializeHasMany: function(record, json, relationship) {
    var key, jsonKey;
    key = relationship.key;
    jsonKey = Ember.String.underscore(key);
    json[jsonKey] = [];

    record.get(key).forEach(function(item) {
      return json[jsonKey].push(item);
    });

    console.log(json)

    return json;
  }
});