backbone.relational – key, keySource, keyDestination

I have the following two models: User and Job.
Each user can have just one job.
The user.attributes and job.attributes look like these (1):

(1)

  • Understanding layouts in Marionette for Backbone.js
  • Best(?) practice for loading & saving relational data in Polymer
  • Backbone-Relational related models not being created
  • Backbone code produces unusable stack traces
  • Backbone-associations vs Backbone-relational
  • How to handle relations in backbone.js
  • user.attributes = {
        id: 1,
        name: 'barName',
        job_id: 5
    }
    
    job.attributes = {
        id: 5,
        name: 'fooJob'
    }
    

    Let’s suppose I want to make a relation between these two models:
    The foreign key should be job_id

    (2)

    User = Backbone.ModelRelation.extend({
        relations: [
            {
                type: Backbone.HasOne,
                key: 'job_id',
                keyDestination: 'job',
                relatedModel: User
            }
        ]
    });
    

    Using the code (2) the result will be:

    (3)

    user.attributes = {
        id: 1,
        name: 'barName',
        job: job.attributes
    }
    

    As you can see the job_id from user.attributes is lost.
    So, if I make a PUT request to the server, the server complains about the missing job_id attribute.
    Any ideas how can I fix (3) in order to keep the job_id in user.attributes like (4)?

    (4)

    user.attributes = {
        id: 1,
        name: 'barName',
        job_id: 5
        job: job.attributes
    }
    

    Reference:
    Paul Uithol – Backbone-relational

  • fetchRelated not fetching related
  • Backbone Relational: Model with 2 collections of the same type
  • Backbone.js - How to handle multiple models with the same id and type? Or how to avoid that situation
  • Backbone-associations vs Backbone-relational
  • Passing urls to relational collections in backbone
  • Backbone-relational cannot instantiate two RelationalModel objects
  • One Solution collect form web for “backbone.relational – key, keySource, keyDestination”

    The workaround for me was to change the way the server reads the JSON posed.

    So the server would read {user:{job:{id:1}}} rather than {user:{job_id:1}}

    Note that we include a sub-object with an id attribute rather than use the job_id flat attribute.

    Depending on which server side framework this can be configured.