Monday, 7 July 2008

Building a Basic Project

This is a brief overview of creating a Rails project. There are plenty of alternatives out there, but I felt there would be something missing if I skipped this.

A Ruby on Rails application revolves around the MVC model. In this design pattern each table in the database corresponds to a model. The model is a class (in the object-orientated sense) that inherits from ActiveRecord, and ActiveRecord handles all the basic database interactions. It is quite possible that your model will have no code in it at all.

For each model, there is usually one controller. The controller accepts the requests from the user, and decides how they will be handled.

For each controller they may be a number of views. Each view is a web page template (rather than a ruby program as such), invoked as a response by the controller.

Rails provides a way to generate the bare bones very easily - this is is big strength. Once you get outside the simple web application, Ruby provides the flexibility to allow you to do anything, but suddenly it gets much more complicated. So forget that for now...

To build a simple web application in NetBeans 6.1:
File - New Project
This builds the directory structure.

Create database (you need MySql running and connected at this point):
Right click your project name: Run Rake Task - db - create

Create the scaffold (the bare bones of your MVC system for one table)
Right click your project name: Project -> Generate Generate: scaffold
In the dialogue box put in the model name, that is the name of the table, in the singular, in CamelCase. For the attribute pairs, these are the column names with the type, for example:

You can put in as many as you want (over twenty anyway), separated by spaces. Types include: string, text, integer, references. Click okay, and Rails will create your model, controller and some default views for doing basic CRUD operations.

The next step is to migrate your database. Rails will only generate a file that specifies the table, this step gets that specification into the SQL database.
Right click your project name: Migrate Database - To Current Version

At this point, the web server can be run, and entries added, etc.

My next few posts will look more at the model, the controller and the views.

Note 1: The official NetBeans tutorial has the scaffold generated before the database is created. Either way works, but their way leads one to think the scaoffolds are generated once per project, like database creation. In fact you can generate numerous scaffolds.

Struggling with Ruby: Contents Page

No comments: