Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RelationalModel relation field at NULL after job's done

I got a wtf problem that I can't figure out. I explain :

I have a model named Product :

var Product = Backbone.RelationalModel.extend(
{
    urlRoot: Backbone.rootApiUrl + '/products',
    defaults: {
        id: '',
        name: '',
        description: '',
        current_price: '',
        categories: '',
        duration: '',
        shipping_cost: '',
        start_date: '',
        user_id: null,
        is_buy_it_now: ''
    },

    relation: [{
        type: Backbone.HasOne,
        key: 'user_id',
        relatedModel: User,
        autoFetch: true
    }]
});

My field user_id is a foreign key for one User (which is also a Model in Backbone) :

var User = Backbone.RelationalModel.extend(
{
    urlRoot: Backbone.rootApiUrl + '/users',
    defaults: {
        id: '',
        name: '',
        email: '',
        firstname: '',
        lastname: '',
        password: '',
        card_nb: '',
        cart_total: ''
    }
});

My fetch relations work perfectly in each separate model. But when i put a relation between the Product.user_id and my User model, a wtf error occurs.

I've tried everything possible : all the keys (keySource, keyDestination ........... with all values possibles). I've even put breakpoints into the Relation Lib to be able to watch what happened ... Nothing to say. Even StackOverflow doesn't know this bug :P (Or i badly searched)

The final problem is :

  • My product is correctly sent by the API and set in Backbone (OK).
  • The field user_id is first set at a number by the Product API response, and then put at NULL by Relational instead of being replaced by the object User (WHY ?)
  • When I watch my network debugger, Relational calls the API for the User object (it's all right here) with the user_id number (OK). The server response is good, with the right user in JSON (OK). But Relational doesn't bind this response object with the field user_id, which is now .... NULL (NOT OK).
    • So I got a User object lost (but I can console.log() it if I put a success function in my autoFetch), not correctly linked to his parent Product with the field user_id.

EDIT : a JSFiddle is available here http://jsfiddle.net/gjdass/WNWrm/ (Be careful, the API can be long to respond, about 10sec, it's normal).

Thanks in advance :/ Sorry for the time you may take for this.

like image 847
gjdass Avatar asked Mar 29 '14 02:03

gjdass


1 Answers

Does it behave any differently if you remove the default value of user_id? I wonder if it's fetching the relation and then applying the default value of null.

You might also try setting Backbone.Relational.showWarnings to true if it isn't already, and check your console for any warnings.

like image 175
Peter G Avatar answered Oct 06 '22 00:10

Peter G