Quantcast
Viewing all articles
Browse latest Browse all 8068

Updating differences in models in collection with new information from a JSON array

I have a model that persists to sqllite.

I have to query a different system to get some data (it's in XML and then I massage it some and turn it into JSON which is working fine) then I want to use that new data to update any changes to the models that have already been persisted or add any items that don't already exist.

I'm struggling a bit with how the ID's should be handled and how the models and collection should be updated/added.

In SQL directly I'd do something like this where I update it based on the address:

db.execute('UPDATE devices SET name=?,sortId=?,displayName=?,showInView=?,type=?,parent=? WHERE address=?',name,sortId,displayName,showInView,type,parent,address);
In my collector I was trying to do something like this and it seems to mostly work but is there a better way to do this and is the ID setup write using the idAttribute with the address like that?
//data is massaged JSON and came back earlier from an external system
    _.each(data,function(item){
        _.defaults(item,{displayName:item.name});
    });
    Ti.API.info("List Of All devices: " + JSON.stringify(data));
 
    var deviceCol = Alloy.Collections.device;  //Alloy.Collections.device is defined in alloy.js
    deviceCol.fetch();
 
  //Save all of the updated records in the collection.
    _.each(data, function(item){
        var device = deviceCol.get(item.address);
        if(device) {
            device.save(item, {silent:true});
        }else{
            deviceCol.add(item);
        }
    });
My model looks like this:
exports.definition = {
    config : {
        "columns" : {
//            "id" : "INTEGER PRIMARY KEY AUTOINCREMENT",
            "sortId" : "integer",
            "name" : "TEXT",
            "displayName" : "TEXT",
            "address" : "TEXT",
            "showInView" : "BOOLEAN",
            "type" : "TEXT",
            "parent" : "TEXT"
        },
        "defaults" : {
            "sortId" : 0,
            "name" : "",
            "displayName" : "",
            "address" : "",
            "showInView" : 0,
            "type" : "unknown",
            "parent" : "unknown"
        },
        "adapter" : {
            "type" : "sql",
            "collection_name" : "devices",
            "idAttribute": "address"
        }
    },
 
    extendModel : function(Model) {
        _.extend(Model.prototype, {
 
        });
        // end extend
 
        return Model;
    },
 
    extendCollection : function(Collection) {
        _.extend(Collection.prototype, {
 
        });
        // end extend
 
        return Collection;
    }
};

Viewing all articles
Browse latest Browse all 8068

Trending Articles