TAGS :Viewed: 11 - Published at: a few seconds ago

[ model.save() timing issue in ember-data with belongsTo relationship ]

I have two models (source and problem) and I am saving an instance with relation to the other when click is triggered through the UI.

App.SourcesController = Ember.ArrayController.extend
  actions:
    addProblem: (source) ->
      problem = @store.createRecord('problem',
        detectedOn: new Date(),
        source: source
      )
      problem.save().then (problem) ->
          # handle success
        ,(e) ->
          # handle error
      false

<p>I am certain that <code>source</code> is present when inside the <code>addProblem</code> action, but when the client actually serializes the model and sends the request, <code>detectedOn</code> attribute is present, but <code>source_id</code> is nowhere to be found.</p>

<p>Now, here is the interesting part.</p>

<p>When I wrap the save code in <code>setTimeout</code>, both <code>detectedOn</code> and <code>source_id</code> do get sent to the server:</p>

<pre class="lang-coffee prettyprint-override"><code>App.SourcesController = Ember.ArrayController.extend
  actions:
    addProblem: (source) -&gt;
      problem = @store.createRecord('problem',
        detectedOn: new Date(),
        source: source
      )
      setTimeout -&gt;
        problem.save().then (problem) -&gt;
            # handle success
          ,(e) -&gt;
            # handle error
        , 1
      false

It seems to me that it's a timing issue within Ember's cycle, or perhaps I am missing something?

How can I get rid of the setTimeout? I should not be doing this every time I save.

Answer 1


I solved this by setting the inverse relationship manually when resolving the promise.The following should work for you:

App.SourcesController = Ember.ArrayController.extend
  actions:
    addProblem: (source) ->
      problem = @store.createRecord('problem',
        detectedOn: new Date(),
        source: source
      )
      problem.save().then (problem) ->
          source.get('problems').addObject(problem)
        ,(e) ->
          # handle error
      false