1

I am trying to fetch all clients, who have nested client-contacs (people). I am having some trouble getting the client-contact collection who belongs to the client/company. If I try to get the collection I get nothing. BTW, I am new at backbone and related stuff.

Here is the code I run at the console to show my problem.

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)

if I run c.get('contacts').fetch() I get all "client-contacts" not only those who are related. Could be an URL issue? What i am missing...?

Thanks.

Here is the code of the models:

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'
tomasbarrios
  • 813
  • 9
  • 15

1 Answers1

1

I am facing similar problem and haven't got an answer yet. But I may be able to share some thought with you.

I am guessing your json structure is:

/clients/: {id: 1, name: "Name"}
/client_contacts/: [{id: 1, client: 1}, {id: 2, client: 1}]

Then you need change /clients/ to be {id: 1, name: "Name", contacts: [1, 2]} to let backbone-relational figure out the relation.

Another problem is you use /client_contacts as url for ClientContactsCollection, this is why you got all contacts back, because /client_contacts is request for all contacts. You many want to check http://backbonerelational.org/#example-person for details.

If you don't want include contacts id in /clients/, then we are facing same problem then: Backbone-relational hasmany best practices

Community
  • 1
  • 1
xzhang
  • 563
  • 6
  • 18
  • 1
    I finally change from backbone-relational to this approach https://tutsplus.com/lesson/nested-collections/, it works pretty nice so far. – tomasbarrios Apr 12 '13 at 18:43