Ruby On Flex

In Flex on Rails we walked through how to generate data in rails to be consumed by a Flex UI. Now to close the loop lets demonstrate how to post information from Flex to Ruby on Rails. For this example we are going to create a user login UI in Flex and have a rails action validate the user name and password. To get started lets show the MXML code for the Flex UI:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=""
	layout="horizontal" horizontalAlign="center" verticalAlign="middle"


      private function getback( event:ResultEvent ):void {
        panel.title = "Login "+event.result.login

    id="loginSubmit" url="http://localhost:3000/mycontroller/login"

  <mx:Panel id="panel" title="Login"
    paddingBottom="10" paddingTop="10"
    paddingLeft="10" paddingRight="10"
      <mx:Label text="Username"/>
      <mx:TextInput id="username"/>
      <mx:Label text="Password"/>
      <mx:TextInput id="password"/>
    <mx:Button label="Submit" click="loginSubmit.send()"/>

mx:HTTPService element. The HTPPService object will send data defined in the content of the mx:request tag. In this case, the username and password elements will be used as parameter names for the data. Also notice that the text between the curly braces will resolve to ActionScript code which returns the text entered in the identified mx:TextInput field.

Now that the Flex UI code has been detailed lets proceed to what we can do in rails. I won’t get into the details of user authentication here, perhaps in another post, so lets assume that the method to authenticate the user does the right thing. The values submitted from the mx:HTTPService element in Flex are available in the rails params hash. Here the rails action to authenticate a username and password.

def login
  @user = User.authenticate(params[:username], params[:password])
  render :layout => false

To communicate the success or failure of the user authentication render an xml document. For this example, create a login.rxml view and add the following:

if @user.nil?
  xml.login "failure"
  xml.login "success"

Technorati Tags: , , , , ,

Leave a Reply