The Source for Java Technology Collaboration
User: Password:
Register | Login help    

Search

Online Books:
java.net on MarkMail:


Database-enabled Hello World RoR app

Posted by arungupta on May 16, 2007 at 3:22 PM PDT

UPDATE: Simplified steps for GlassFish V2 are available here and for V3 here.

Follow up from here.

In this post I show how a Rails app can talk to database. Here are the steps I followed:

  1. Deploy a RoR application as WAR on GlassFish using these steps.
  2. Modify the application such that "Hello World!" is read from the controller instead of defined in the view (this is natural to RoR programmers anyway!).
    1. Define a new variable in controller as '@hello_string = "Hello World!"'.
    2. Replace the string in view with '<%= @hello_string %>'.
  3. Download and install MySQL Community Server 5.0 and MySQL Connector/J 5.0.5.
  4. Create database using the command: 'mysqladmin -u root create helloworld_development'.
  5. Right select the NetBeans project, select 'Generate', select 'model', specify the arguments as 'table1', click 'OK'. This will generate, in NetBeans project, Database Migrations, migrate, 001_create_table1s.rb.
  6. Open 001_create_table1s.rb, change self.up helper method such that it looks like:
    def self.up
      create table :table1s do |t|
        t.column :data, :string
      end
    end
  7. Right-select NetBeans project, select 'Run Rake Target', 'db', 'migrate'. This generates the appropriate database tables.
  8. In NetBeans Runtime tab, right click on 'Databases', 'New Connection ...'.
    1. In Name, select 'New Driver ...' and specify the location of mysql-connector-java-5.0.5-bin.jar from the MySQL Connector/J installation directory.
    2. In Database URL, give 'jdbc:mysql://localhost:3306/helloworld_development'.
    3. Expand the newly added database node, expand Tables, right-select 'table1s', select 'Execute Command ...'.
    4. Enter the following SQL "insert into table1s values (1, 'Hello from database')". Run the SQL.
  9. Change the controller such 'hello_string' is initialized from the database. This is a contrived example but still convey the concept. Anyway, The code looks like:

    @hello_string = Table1.find(1).data
  10. Start MySQL database by giving the following command:

    mysqld --console
  11. Save all the files and refresh the page in the browser. If your controller name is 'say' and view is 'hello', then the URL will be 'http://localhost:3000/say/hello'. The browser will now display 'Hello from database'.

In a later post, I'll describe how this same application can be deployed as WAR in GlassFish V2.

Technorati: glassfish rubyonrails ror netbeans

Related Topics >> Web Applications      
Comments
Comments are listed in date ascending order (oldest first)