我在创建一个新的模型表单json时遇到了一些问题,该表单包含嵌套的属性,应该将其解析为集合。在这里我展示了我如何得到错误:
(感谢任何帮助)
1) 我创建了一个类似的用户
user = new App.Models.User( {"email":"tom@gmail.com","id":1,"user_cities_attributes":[{"city_id":431,"user_action":"to-visit","user_id":1}] }
2) 然后我在控制台中检查发生了什么,集合没有创建。:S
user.get('user_cities')
> undefined # where is my collection?! :(
user.get('user_cities_attributes')
> [Object] # mmm weird...
如果我在之后尝试将新模型添加到集合中。。。
cities = new App.Collections.CitiesCollection()
cities.fetch()
userCity = new App.Models.UserCity( { user: user, city: cities.first(), user_action: "to-visit" } )
现在一切似乎都很好。。。发生了什么????
user.get('user_cities')
> Backbone.Collection {length: 20, models: Array[20], _byId: Object, model: function, user: User…}
user.get('user_cities_attributes')
undefined
模型
class App.Models.User extends Backbone.RelationalModel
paramRoot: 'user'
urlRoot: 'users'
defaults:
name: null
class App.Models.UserCity extends Backbone.RelationalModel
paramRoot: 'user_city'
urlRoot: 'user_cities'
defaults:
user_action: null
relations: [{
type: Backbone.HasOne,
key: 'user',
relatedModel: 'App.Models.User',
collectionType: 'App.Collections.UsersCollection',
keySource: 'user_id',
includeInJSON: 'id',
reverseRelation: {
key: 'user_cities',
keySource: 'user_cities_attributes',
includeInJSON: 'id'
}
},
{
type: Backbone.HasOne,
key: 'city',
relatedModel: 'App.Models.City',
collectionType: 'App.Collections.CitiesCollection',
includeInJSON: 'id',
keySource: 'city_id',
reverseRelation: {
key: 'users',
includeInJSON: 'id'
}
}]
class App.Models.City extends Backbone.RelationalModel
paramRoot: 'city'
urlRoot: 'cities'
defaults:
name: null
relations: [{
type: Backbone.HasMany,
key: 'places',
relatedModel: 'App.Models.Place',
collectionType: 'App.Collections.PlacesCollection',
keySource: 'places_attributes',
# parse: true,
includeInJSON: 'id',
autoFetch: true,
reverseRelation: {
key: 'city',
includeInJSON: 'id'
}
# 'relatedModel' is automatically set to 'Zoo'; the 'relationType' to 'HasOne'.
}]
查看有关reverseRelation和使用coffeescript的说明(来自:http://backbonerelational.org/#relations-reverseRelation):
请注意,如果在模型,但实际上并没有创建该模型的实例,它是可能的initializeRelationship永远不会被调用,并且reverseRelation将不会初始化。当扩展时可能发生这种情况已被重写或重新定义为CoffeeScript中的。请参阅设置。
然后尝试使用.setup,如下所述:http://backbonerelational.org/#RelationalModel-设置