Not able to update model using Alloy in Titanium Appcelerator

2.7k views Asked by At

I am trying to update a model in a collection in Titanium using Alloy.

This code is not working:

var contactos = Alloy.Collections.instance('Contact');

var contacto = contactos.get({id: 3});
// Output: {id:3, name:'Juan 3', marcado: 1}
Ti.API.debug('get: ' + JSON.stringify(contacto));

contacto.set({marcado: 0});
// Output: {id:3, name:'Juan 3', marcado: 0}
Ti.API.debug('set: ' + JSON.stringify(contacto));

contacto.save();    
contactos.fetch();

// Output: [{id:3, name:'Juan 3', marcado: 1},{...},{...}]    
Ti.API.debug('despues de save: ' + JSON.stringify( JSON.stringify( contactos ) ));

While this is working:

var contactos = Alloy.Collections.instance('Contact');

var contacto1 = Alloy.createModel('Contact');
// Output: {id:null, name:'', marcado: 0}
Ti.API.debug('createModel: ' + JSON.stringify(contacto1));

var contacto2 = contactos.get({id: 3});
// Output: {id:3, name:'Juan 3', marcado: 1}
Ti.API.debug('get: ' + JSON.stringify(contacto2));

contacto1.set( contacto2 );
contacto1.set({marcado: 0});
// Output: {id:3, name:'Juan 3', marcado: 0}
Ti.API.debug('set: ' + JSON.stringify(contacto1));

// elimino el contacto 2
contacto2.destroy();

contacto1.save();   
contactos.fetch();

// Output (last object): [{...},{...},{...},{...},{id:3, name:'Juan 3', marcado: 0}]    
Ti.API.debug('despues de save: ' + JSON.stringify( JSON.stringify( contactos ) ));

But: - First option is working fine to save NEW models (not existing in collection).

Update a model should be a very easy task, but I am not able to do it.

Any idea about the possible problem?

Thank you.

J. Pablo.

1

There are 1 answers

0
damian On

I had the same problem, this is how I fixed it: When you define your model, you have to explicitly declare the primary key, like this:

exports.definition = {
config: {
    columns: {
        "id": "INTEGER PRIMARY KEY",
        "name": "TEXT",
        "marcado": "INTEGER"
    },
    adapter: {
        type: "sql",
        idAttribute: "id"
    }
},
    extendModel: function(Model) {
    _.extend(Model.prototype, {
        idAttribute: "id",
   ...
        return Model;
    }
};

It's not enough to declare idAttribute.