Требуется Sencha Touch RestProxy с примером Rails - PullRequest
2 голосов
/ 02 марта 2011

У меня есть следующая модель

Ext.regModel("Entries", {
    fields: [
        {name: "id",             type: "int"},
        {name: "title",           type: "string"},
        {name: "bought",         type: "boolean"},
   ],
    proxy: {
        type: 'rest',
        url: '/lists',
        format: 'json',
        reader: {
            type: 'json'
        }
    }
});

Затем у меня есть список, который заполняется из этой модели

...
store: new Ext.data.Store({
            model: "Entries",
            autoLoad: true,
            remoteFilter: true
        }),
...

Список заполнен правильно.Но когда я пытаюсь выполнить следующее

   listeners: {
            itemswipe: function (record, index, item, e) {
                var el = Ext.get(item);
                el.toggleCls("crossedOut");
                var store = record.getStore();
                var rec = store.getAt(index);
                if (el.hasCls('crossedOut')) {
                    rec.set('bought', true);
                    rec.save({
                        success: function() {
                            console.log("Saved!");
                        }
                    });
                } else {
                    console.log('not crossed out');
                    rec.set('bought', false);
                    rec.save({
                        success: function() {
                            console.log("Saved!");
                        }
                    });
                }
            }
        }

, когда происходит событие swipe, я получаю следующую ошибку

Uncaught TypeError: Cannot read property 'data' of undefined gsencha-touch.js:6
(anonymous function) sencha-touch.js:6
Ext.data.Connection.Ext.extend.onCompletesencha-touch.js:6
Ext.data.Connection.Ext.extend.onStateChangesencha-touch.js:6
(anonymous function)

Я понимаю, что существует некоторая проблема с полезной нагрузкойЯ возвращаюсь, но не могу найти правильный пример, и все мои догадки не работают.

В бэкэнд я возвращаю следующее

format.json {render :json => {:data => @list, :success=> true, :id => @list.id}}

Ответы [ 2 ]

7 голосов
/ 02 марта 2011

Я использую предварительный просмотр ExtJS 4, но он должен работать так же с Sencha Touch.Ваша проблема может быть связана с вложением возвращенного json.Вот что работает для меня.

В контроллере Rails:

def index
  respond_with @entries = Entry.all do |format|
    format.json { render :json => {:success => true, :data => @entries, :total => @entries.count} }
  end
end

def show
  respond_with @entry = Entry.find(params[:id]) do |format|
    format.json { render :json => {:success => true, :data => [@entry]} }
  end
end

def create
  respond_with @entry = Entry.create(params[:records][0]) do |format|
    format.json { render :json => {:success => true, :data => [@entry]} }
  end
end

def update
  @entry = Entry.find(params[:id])
  @entry.update_attributes(params[:records][0])
  respond_with @entry do |format|
    format.json { render :json => {:success => true, :data => [@entry]} }
  end
end

Модель ExtJS:

Ext.regModel("Entries", {
    fields: [
            {name: "id",             type: "int"},
        {name: "title",           type: "string"},
        {name: "bought",         type: "boolean"},
   ],
    proxy: {
        type: 'rest',
        url: '/lists',
        format: 'json',
        reader: {
            type: 'json',
            root: 'data',
            record: 'entry'
        }
    }
});

Два отличия от того, что вы сделали:

1 / Опция записи в Reader указывает ExtJS искать вложенные записи в json.Он говорит, что нужно искать:

data: [
    {
        entry: {
            id: 1,
            title: "Title 1",
            bought: true
        }
    }
]

вместо:

data: [
    {
        id: 1,
        title: "Title 1",
        bought: true
    }
]

Альтернативой настройке свойства записи в ридере может быть отключение вложенного json в Rails путем сброса этогов конфигурацию вашего приложения:

config.active_record.include_root_in_json = true

2 / При возврате одной записи вывод json должен быть таким же, как коллекция, за исключением того, что у вас есть только одна запись.

Sencha Touch иДокументация по ExtJS 4 иногда бывает немного скудной, и я обнаружил, что разбирать примеры - лучший способ научиться.

HTH

2 голосов
/ 25 июня 2012

Я столкнулся с подобной проблемой при отправке одной записи вместо магазина.Установка объекта записи с именем вашей записи в качестве rootProperty решает проблему.

writer: {
  type         : 'json',
  rootProperty : 'your_record'
}
...