我在用户和对话之间的应用程序中有多对多的关系
App.User = DS.Model.extend,
conversations: DS.hasMany('App.Conversation')
App.Conversation = DS.Model.extend
participants: DS.hasMany('App.User')
但每次我创建和保存对话时,ember都会尝试保存每个参与者,包括相关对话的ID。但我希望与此完全相反,我希望它只更新那个对话并发送相关的participant_ids。
有没有办法让它发挥作用?
到目前为止我尝试了什么:
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
那么有没有办法让它发挥作用?
答案 0 :(得分: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'