Experiences on the Front Lines of User Interfaces and Web Development

Use Rails url_for in Ext grids

In rails apps, it is best practice to always use link_to and url_for when generating URLs. This prevents your application from having hard-coded links that may break if you refactor controllers later. It also allows an easy way of creating links that send a put/post/delete command to your server.

I found that I wanted that abstraction and power in an Ext grid that was in a view. If you have used Ext grids at all, you know that you set up a store and populate it with data (json object, async request, etc) and then give it some column information and Ext does the rest. In other words, it iterates across your records and displays the rows, so there's no way to use <%= link_to ... %> for a cell in each row because the rendering is done client-side in JavaScript.

My quick solution, that perhaps some will find helpful:

var delete_link_template = '<%= link_to( 'Delete', { :controller => 'my_controller', :action => 'destroy', :id => '__id__' },
{ :method => :delete, :confirm => 'Are you sure you want to leave this item?' } ).gsub( "\'", "\\\\'" ) %>';

function actions_renderer( val, metadata, record ) {
var object_id = record.get("id");
return val + ': ' + delete_link_template.replace( "__id__", object_id );
}


// this is a portion of an example Ext grid being declared. Notice it uses 'actions_renderer', which is the function defined above
var my_grid = new Ext.grid.GridPanel(
{
columns:
[
...,
{ header: "Manage", width: 140, dataIndex: 'name', renderer: actions_renderer }
],
...
} );
comments powered by Disqus