ExtJS with Rails 3

March 6th, 2011 3 Comments »

In order to make ExtJS play nicely with Rails, the following tweaks are needed:

On the ExtJS javascript side, the following things are needed:

1. Ask server to server JSON:

Ext.Ajax.defaultHeaders = {'Accept': 'application/json'};

2. RailsJsonStore:

Ext.data.RailsJsonStore = Ext.extend(Ext.data.JsonStore, {
    constructor: function(config) {
        Ext.data.RailsJsonStore.superclass.constructor.call(this, Ext.applyIf(config, {
            messageProperty: 'message', //for store.reader.getMessage()
            restful: true,
            url: '/'+ config['root'] + 's',
            writer: {encode: false}
        }));
    }
});
Ext.reg('railsjsonstore', Ext.data.RailsJsonStore);

3. XSRF protection:

Ext.Ajax.on('beforerequest', function(o) {
        var csrf = Ext.select("meta[name='csrf-token']").first();
        if (csrf) {
                o.defaultHeaders = Ext.apply(o.defaultHeaders || {}, {'X-CSRF-Token': csrf.getAttribute('content')});
        }
});

On Rails side:

config.active_record.include_root_in_json = false

Pages

Adsense