Jan
10

In this tutorial the basics of creating a very simple Link Manager that uses an SQLite database in Rails 2.02 will be covered. This will hopefully be the first in a series of many tutorials highlighting the simplicity and power of Ruby on Rails. This tutorial assumes that you have Ruby, and Rails already installed.

Note: $ will be used to indicate the command prompt.

Install SQLite3 by downloading the pre-compiled binary and the command line program from http://www.sqlite.org/download.html. Unzip all three files to the Ruby bin directory (C:\ruby\bin). Use gem to install the Ruby bindings:

$ gem install sqlite3-ruby

We will call our Link Manager, mylinks. Let’s start by creating a Rails application called mylinks:
$ rails mylinks

The following is output to the console:

create
create app/controllers
create app/helpers
create app/models
create app/views/layouts
create config/environments
create config/initializers
create db
create doc
create lib
create lib/tasks
create log
create public/images
create public/javascripts
create public/stylesheets
create script/performance
create script/process
create test/fixtures
create test/functional
create test/integration
create test/mocks/development
create test/mocks/test
create test/unit
create vendor
create vendor/plugins
create tmp/sessions
create tmp/sockets
create tmp/cache
create tmp/pids
create Rakefile
create README
create app/controllers/application.rb
create app/helpers/application_helper.rb
create test/test_helper.rb
create config/database.yml
create config/routes.rb
create public/.htaccess
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/boot.rb
create config/environment.rb
create config/environments/production.rb
create config/environments/development.rb
create config/environments/test.rb
create script/about
create script/console
create script/destroy
create script/generate
create script/performance/benchmarker
create script/performance/profiler
create script/performance/request
create script/process/reaper
create script/process/spawner
create script/process/inspector
create script/runner
create script/server
create script/plugin
create public/dispatch.rb
create public/dispatch.cgi
create public/dispatch.fcgi
create public/404.html
create public/422.html
create public/500.html
create public/index.html
create public/favicon.ico
create public/robots.txt
create public/images/rails.png
create public/javascripts/prototype.js
create public/javascripts/effects.js
create public/javascripts/dragdrop.js
create public/javascripts/controls.js
create public/javascripts/application.js
create doc/README_FOR_APP
create log/server.log
create log/production.log
create log/development.log
create log/test.log

Lots of folders and files have been created! At first this may seem a little overwhelming, but having an application structure created for you will end up saving you heaps of time. It won’t take long to get familiar with the structure. The most important folders/files are:

  • mylinks\app
    The app folder is where the application code will reside. This folder contains sub-folders for your models, views, controllers and view helpers.
  • mylinks\config
    The config folders contain files to configure your Rails application. We’ll take a look at mylinks\config\database.yml in this tutorial, as this is where the database settings for the SQLite database are stored.
  • mylinks\log
    Log files are stored here. Rails stores logs in separate files based on which mode your application is running eg development.log or production.log
  • mylinks\public
    The index.html file and error files (eg 404.html, 422.html and 500.html) are stored here. There are also subfolders to store javascripts, stylesheets and images. The /javascripts folders contains the Prototype and Scriptaculous libraries.
  • mylinks\test
    The test folder contains folders for you to store you unit, functional and integration test scripts. With Rails you’ll have no excuse to put off writing tests.

Change to the mylinks folder:

$ cd mylinks

Take a few minutes to explore the folder structure on your own.

There is already an index.html in the public folder, so we are able to fire up WEBrick (the web server that Rails uses by default):
$ ruby script/server

The following is output to the console:

=> Booting WEBrick…
=> Rails application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with –help for options
[2008-01-06 17:05:20] INFO WEBrick 1.3.1
[2008-01-06 17:05:20] INFO ruby 1.8.4 (2006-04-14) [i386-mswin32]
[2008-01-06 17:05:20] INFO WEBrick::HTTPServer#start: pid=1400 port=3000

As you can see the WEBrick server runs on port 3000. Point your browser to http://localhost:3000 and you’ll be riding on Rails.

Displaying the index.html file

A Rails 2.02 application is by default configured to store data in an SQLite 3 database. You can take a look at the database configuration settings in the config\database.yml file - a YAML file. Ain’t it great not to edit an XML configuration file? You’ll notice that Rails has separate databases for different regions/environments eg development, test and production. If you were dealing with a MySQL database, you’d have to enter a username and password.


# SQLite version 3.x
#   gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
adapter: sqlite3
database: db/development.sqlite3
timeout: 5000

# Warning: The database defined as 'test' will be erased and
# re-generated from your development database when you run 'rake'.
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
database: db/test.sqlite3
timeout: 5000

production:
adapter: sqlite3
database: db/production.sqlite3
timeout: 5000

The mylinks application needs to allow us to create, read, update and delete links (in other words a CRUD). This application only needs a single table called links with columns to store the title, url and description for each link. In any other framework creating this simple example would take some work - database table creation scripts, ORM config, web app config, writing model, controller and view code, etc. With Rails we can generate all of this code and more in 1 line with the scaffold command:

$ ruby script/generate scaffold Link title:string url:string description:text

We have told Rails to make a model called Link. Models are always in singular form - this is a Rails convention. We also tell scaffold that the model must have a title, url and description and specify the datatypes for each of these fields/columns at the same time. Scaffold then goes off and does a lot of hard work. Heres the console output:

exists app/models/
exists app/controllers/
exists app/helpers/
create app/views/links
exists app/views/layouts/
exists test/functional/
exists test/unit/
create app/views/links/index.html.erb
create app/views/links/show.html.erb
create app/views/links/new.html.erb
create app/views/links/edit.html.erb
create app/views/layouts/links.html.erb
create public/stylesheets/scaffold.css
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/link.rb
create test/unit/link_test.rb
create test/fixtures/links.yml
create db/migrate
create db/migrate/001_create_links.rb
create app/controllers/links_controller.rb
create test/functional/links_controller_test.rb
create app/helpers/links_helper.rb
route map.resources :links

Wow! Scaffold has gone off and created the model, view and controller code. That alone would be awesome, but Scaffold has done even more - it has also created a script to create the database table (known as a Migration) and a functional test. I told you there was no excuse to not write tests - well they are even written for you! Just make sure you keep em up to date as you modify the code!

Let’s take a look at the script used to create a database - a file called db/migrate/001_create_links.rb:


class CreateLinks < ActiveRecord::Migration
def self.up
create_table :links do |t|
t.string :title
t.string :url
t.text :description

t.timestamps
end
end

def self.down
drop_table :links
end
end

Migration scripts need to reverse there actions hence the inclusion of drop_table. In later tutorials you’ll learn to use Migrations to make and undo changes to database tables - thats why Migrations are versioned (001_).

Use rake to create the database:

$ rake db:create

Run the first migration:

$ rake db:migrate

rake db:migrate
(in C:/rails2/mylinks)
== 1 CreateLinks: migrating ================================================
– create_table(:links)
-> 0.1250s
== 1 CreateLinks: migrated (0.1250s) =========================================

Before we head off to test the mylinks application, I have some magic to show you. Open the Link model which is stored in the mylinks\app\models\link.rb file.


class Link < ActiveRecord::Base
end

The Link class/model has no code! Your eyes are not deceiving you! The model just needs to inherit from ActiveRecord::Base and the fields/columns in the Links table are dynamically mapped to the model. Remember that the model name is singular while the table name is plural.

As much as I love that the Model has no code, I think that it is wise to ensure that the title and url are not blank. In Rails validation is added directly to the model:


class Link < ActiveRecord::Base

validates_presence_of :title, :url

end

If you have shut WEBrick down, fire it up again:

$ ruby script/server

Point your browser at http://localhost:3000/links and you’ll see that you currently have no links stored in your mylinks application. Luckily there is a ‘New link’ link, so click it.

The CRUD with no links

The form to create a link is displayed (http://localhost:3000/links/new). Enter the title and url of a link you remember. The only url I could remember while writing this tutorial is http://www.google.com. Click the Create button.

Add a Link

Yeah! A confirmation page (http://localhost:3000/links/1). Click on the Back link.

Confirmation Page

http://localhost:3000/links now gives us an interface to Show, Edit or Destroy our links.

And look the validation actually works:

Validation Error Messages

Well, we have reached the end of this tutorial or should I say tutorail! Don’t worry Part 2 will be along soon and promises to explain how models, controllers and views are hooked up in Rails.

In summary it took 5 command to make the mylinks application:

  1. $ rails mylinks
  2. $ cd mylinks
  3. $ ruby script/generate scaffold Link title:string url:string description:text
  4. $ rake db:create
  5. $ rake db:migrate
    Read More   

Comments

[…] Read the rest of this great post here […]


Mark on 12 January, 2008 at 7:34 pm #

scaffolding was removed from Rails 2 so you’ll need to install the scaffolding plugin to making work.


Markus Lux on 12 January, 2008 at 8:23 pm #

great resource! - i’m curious about part 2 :)


dan on 13 January, 2008 at 12:39 pm #

cool tutorial, nice work,……


SoftMind on 13 January, 2008 at 2:30 pm #

Hi,

Nice things shaping up.

How about a real life Tutorial that actually shapes into something interesting and useful.

I am talking about a full fledged dating site in Ruby On Rails. I have not seen any dating site so far in Ruby on rails.

A full fledged Classified site can also do wonders.

Just an Idea.


Derek on 14 January, 2008 at 2:52 am #

Re: scaffold

Scaffolding has not been removed from Rails 2.0. While “dynamic scaffolding” _has_ been removed, this tutorial doesn’t demonstrate that ‘feature’.

Further, the scaffold generator in Rails 2.0 is the old(ish) resource_scaffold.


dan on 18 January, 2008 at 8:05 pm #

Looks nice the tutorial, but to be honest with u i have read so many tutorials about ruby which most of them have the same thing, can you write something which is diferrent, something which ppl never seen? …..


Aneesha on 19 January, 2008 at 5:33 am #

Dan, I hope to write a Rails Tutorial every week. So I’m sure I’ll get to advanced stuff.


Jay Braude on 7 February, 2008 at 4:36 am #

Thank you - I am on Ubuntu trying to learn RoR and am a newbie to both and this worked just fine! Now throw in an AJAX TUTORIAL…


Ralph on 20 February, 2008 at 6:27 am #

I’m new to Rails also, hard to find good tutorials. If anyone is looking for some Rails 2.0 resources check out my site for some links.


[…] “Making a Link Manager (Part 1)” […]


[…] wrote a Rails tutorial. It was meant to be the first of many. I still have plans to complete the series but I’ve had […]


david on 6 July, 2008 at 11:57 am #

Thanks for this great tutorial..

I was only finding old ones.


Post a Comment
Name:
Email:
Website:
Comments: