为了在服务器上坚持多对多的关系,我正在攻击 hasMany 序列化程序添加选项的方法 serialized 在映射中。
hasMany
serialized
这是序列化程序(CoffeeScript):
App.Serializer = DS.RESTSerializer.extend # redefine to make it possible to serialize a relationship by an array of ids # to enable it, a 'serialized' property should be set to 'ids' in the adapter mapping # the key in the hash will be the type of the object in the relation ship + _ids' # example : for an hasMany('App.Category'), the key will be category_ids addHasMany: (hash, record, key, relationship) -> type = record.constructor name = relationship.key serializedType = @serializedType type, name if serializedType is 'ids' key = @singularize(@keyForAttributeName(type, name)) + "_ids" manyArray = record.get name serializedIds = [] manyArray.forEach (record) -> serializedIds.push record.get('id') hash[key] = serializedIds else return @_super hash, record, key, relationship # method to access the serialized option in adapter mapping serializedType: (type, name) -> @mappingOption type, name, 'serialized'
这是一个映射配置例子:
App.Adapter.map App.Product, categories: serialized: 'ids'
有了这个,当我犯了一个 Product json将包含一个键 category_ids 它包含相关类别ID的数组。
Product
category_ids
更新:
要正确使用 App.Serializer 定义后,您应该将其添加到应用程序的适配器:
App.Serializer
App.Adapter = DS.RESTAdapter.extend serializer: App.Serializer
要在您的应用程序中使用此适配器,您必须在商店中进行设置:
App.Store = DS.Store.extend adapter: 'App.Adapter'