Archive for June, 2008

Display Rails associations in a Flex DataGridColumn

Sunday, June 29th, 2008

Frameworks like Ruby on Rails and CakePHP make it easy to set up model associations with belongs_to, has_many, and the ever popular has_and_belongs_to_many. However, getting those associations to show up in a Flex DataGridColumn’s dataField isn’t immediately obvious, you’d assume you could just do parent.child or child.parent but that just gives a blank column. After some digging I found the answer is to use a labelFunction.

In the example below there are two models in Rails, ‘Group’ and ‘Category’, Group has_many Categories and Category belongs_to Group. Here’s the Flex code for the Categories DataGrid, groupName is the labelFunction that spits out a Category’s Group name (equivalent to @category.group.name in ruby):

<?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%">

    <mx:Script>
        <![CDATA[
            import mx.controls.dataGridClasses.DataGridColumn;

            private function groupName( item:Object, column:DataGridColumn ):String
            {
                return item.group.name;
            }

        ]]>
    </mx:Script>

    <mx:DataGrid id="dataGrid" width="100%" height="100%">
        <mx:columns>
            <mx:DataGridColumn headerText="Name" dataField="name" />
            <mx:DataGridColumn headerText="Group" labelFunction="groupName" />
        </mx:columns>
    </mx:DataGrid>

</mx:VBox>