3

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)

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

Lorraine Bernard
  • 13,000
  • 23
  • 82
  • 134

1 Answers1

0

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.

simbolo
  • 7,279
  • 6
  • 56
  • 96