简体   繁体   中英

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

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

Now, here is the interesting part.

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

App.SourcesController = Ember.ArrayController.extend
  actions:
    addProblem: (source) ->
      problem = @store.createRecord('problem',
        detectedOn: new Date(),
        source: source
      )
      setTimeout ->
        problem.save().then (problem) ->
            # handle success
          ,(e) ->
            # 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM