我正在尝试获取所有客户端,这些客户端都嵌套了client-contacs (people)。我在获取属于客户/公司的客户联系人集合时遇到了一些问题。如果我尝试获取集合,则什么也得不到。顺便说一句,我是新的骨干和相关的东西。
下面是我在控制台上运行的代码,用来显示我的问题。
c = new SpencerGrafica.Models.Client({id:1})
c.fetch()
c.toJSON()
Object {id: 1, name: "Name", contacts: Array[0], …}
c.get('contacts').toJSON()
[] # (There should be ONE result, as I set this relation in rails console)如果我运行c.get('contacts').fetch(),我会得到所有的“客户联系人”,而不仅仅是那些相关的联系人。可能是URL问题?我错过了什么...?
谢谢。
以下是模型的代码:
client.js.coffee
class SpencerGrafica.Models.Client extends Backbone.RelationalModel
paramRoot: 'client'
urlRoot: 'clients'
defaults:
id: null
name: null
relations: [{
type: Backbone.HasMany,
key: 'contacts',
relatedModel: 'SpencerGrafica.Models.ClientContact',
collectionType: 'SpencerGrafica.Collections.ClientContactsCollection',
autoFetch: true,
reverseRelation: {
key: 'client',
keySource: 'client_id'
}
}]
class SpencerGrafica.Collections.ClientsCollection extends Backbone.Collection
model: SpencerGrafica.Models.Client
url: '/clients'ClientContact.js.coffee
class SpencerGrafica.Models.ClientContact extends Backbone.RelationalModel
paramRoot: 'client_contact'
urlRoot: 'client_contacts'
defaults:
name: null
email: null
phone: null
class SpencerGrafica.Collections.ClientContactsCollection extends Backbone.Collection
model: SpencerGrafica.Models.ClientContact
url: 'client_contacts'发布于 2013-04-12 06:04:22
我正面临着类似的问题,还没有得到答案。但我也许能和你分享一些想法。
我猜你的json结构是:
/clients/: {id: 1, name: "Name"}
/client_contacts/: [{id: 1, client: 1}, {id: 2, client: 1}]然后,您需要将/clients/更改为{id: 1, name: "Name", contacts: [1, 2]},以便让backbone-relational找出关系。
另一个问题是你使用/client_contacts作为ClientContactsCollection的url,这就是为什么你得到了所有的联系人,因为/client_contacts是所有联系人的请求。您可能希望查看http://backbonerelational.org/#example-person以了解详细信息。
如果您不希望在/clients/中包含联系人id,那么我们将面临相同的问题:Backbone-relational hasmany best practices
https://stackoverflow.com/questions/15938117
复制相似问题