0

我的应用程序中的用户和对话之间存在多对多关系

App.User = DS.Model.extend,
  conversations: DS.hasMany('App.Conversation')    

App.Conversation = DS.Model.extend
  participants: DS.hasMany('App.User')

但是每次我创建和保存对话时,ember 都会尝试保存每个参与者,包括他们相关对话的 ID。但我想要完全相反,我希望它只更新一个对话并发送相关的参与者 ID。

有没有办法让它工作?

到目前为止我尝试了什么:

  • 在用户模型上指定逆键 ( conversations: DS.hasMany('App.Conversation', inverse: 'participants'))
  • 下面的解决方法。

.

App.RESTAdapter = DS.RESTAdapter.extend

  serializer: DS.RESTSerializer.extend
    addHasMany: (hash, record, key, relationship) ->
      type = record.constructor
      name = relationship.key
      serializedHasMany = []

      embeddedType = this.embeddedType(type, name)
      return unless embeddedType is 'always'

      record.get(name).forEach (record) ->
        serializedHasMany.push record.get('id')
      , @

      hash[@singularize(key) + '_ids'] = serializedHasMany

App.RESTAdapter.map 'D4S.Conversation',
  participants:
    embedded: 'always'

之后它将保存包括外键在内的对话,但仍会尝试更新用户,因此我尝试使用自定义请求保存它并重置参与者状态:/

    App.Conversation._createWith = (participants) ->
      conversation = @createRecord()

      participants.forEach (p) ->
        conversation.get('participants').addObject(p)

      # conversation.save()
      adapter = conversation.get('store._adapter')
      adapter.ajax(adapter.buildURL('conversation'), 'POST',
        data: { conversation: conversation.serialize() }
      ).then ->
        conversation.setProperties(arguments[0].conversation)
        conversation.get('stateManager').transitionTo('saved')
        conversation.get('participants').forEach (user) ->
          user.get('stateManager').transitionTo('saved')
        conversation.trigger('didCommit')

      conversation

最终工作了 \o/ 但抛出了下一个错误:(

加载 ember 时不会加载关系,会话参与者属性始终为空 DS.ManyArray

那么有没有办法让它发挥作用?

4

1 回答 1

0

解决方案:实现自己的映射键,不要使用已经使用过的键。这个实现解决了我所有的问题:

serializer: DS.RESTSerializer.extend
  ###
  Custom implementation to realize manySaving mapping
  ###
  addHasMany: (hash, record, key, relationship) ->
    @_super(hash, record, key, relationship)
    type = record.constructor
    name = relationship.key
    serializedHasMany = []

    manySaving = this.manySaving(type, name)
    return unless manySaving

    record.get(name).forEach (record) ->
      serializedHasMany.push record.get('id')
    , @

    hash[key] = serializedHasMany

  ###
  Check if manySaving option for a specific relationship is enabeld
  @param {String} type  The record type (usally a model class)
  @param {String} name  The attribute name of the relationship
  @return {Boolean}
  ###
  manySaving: (type, name) ->
    this.mappingOption(type, name, 'manySaving')

D4S.RESTAdapter.map 'D4S.User',
  conversations:
    manySaving: false

D4S.RESTAdapter.map 'D4S.Conversation',
  participants:
    manySaving: true
    key: 'participant_ids'
于 2013-09-15T12:20:34.653 回答