8

如何在不删除孩子的情况下从 hasMany 关系中删除孩子?

我尝试将孩子的 foreign_key 设置为 null。我也尝试过在父关系上使用 removeObject 。

这是一个例子。

App.Invoice = DS.Model.extend
  lines: DS.hasMany('App.Line')

App.Line = DS.Model.extend
  invoice: DS.belongsTo('App.Invoice')

App.InvoiceController = Ember.Controller.extend
  removeLine: (line) ->
    @get('content.lines').removeObject(line)
    line.set('invoice', null)
    @get('store').commit()

App.InvoiceEditView = Ember.View.extend
  templateName: 'invoice'

App.LineView = Ember.View.extend
  tagName: 'tr'
  templateName: 'line'


#invoice template
<table>
    {{#each content.tasks}}
      {{view App.LineView}}
    {{/each}}
</table>

#line template
<td><a {{action "removeLine" view.context}}>remove</a></td>
<td>{{description}}</td>
<td>{{price}}</td>
<td>{{price}}</td>

我目前正在使用

jquery 1.8.2
ember.js v1.0.pre-4
ember-data v11
4

2 回答 2

2

remove()函数中,它commit()是然后remove()再次调用。这将导致“setProperty in state rootState.loaded.updated.inFlight”错误,因为在 Ajax 请求为inflight时无法更改记录。

如果您的意图是实际删除Line,从而将其从hasMany关联中删除,那么我建议使用remove()如下函数:

remove: function(event) {
  var item = event.context;
  if (item.get('isDeleted')) return;
  item.deleteRecord();
  App.store.commit();
  return item;
}

Note that once something has be marked for deletion by deleteRecord(), it will remain live in Ember with isDeleted == true until a commit() completes successfully. You may want to add a classNames binding to hide it with CSS once it's marked for deletion:

#line template
<tr {{bindAttr class="isDeleted"}}>
  <td><a {{action "removeLine" target="view"}}>remove</a></td>
  <td>{{description}}</td>
  <td>{{price}}</td>
  <td>{{price}}</td>
</tr>

With CSS like:

.is-deleted { display: none; }
于 2012-10-07T01:02:47.140 回答
1

It seems that setting invoice to an empty string works.

 App.InvoiceController = Ember.Controller.extend
   removeLine: (line) ->
     @get('content.lines').removeObject(line)
     line.set('invoice', '')
     @get('store').commit()
于 2013-01-28T19:57:31.997 回答