Lesson 2 -- Databases

In writing software for any platform, we need to be able to do 3 things:
1. get input from the user
2. store the information
3. output results to the user

We have , on the Rails platform, learnt how to output text to the user
via a dynamic web page. In this chapter we deal with databases. In the
next chapter, we will see how to get input from the user, and you will be
ready to start writing your application.

Imagine we wish to create a database for books, and wish to track their
names, numbers and authors. In Rails, we simply, on the command line,
go to the root folder of the application, and type the following

script/generate scaffold book name:string num:integer author:string
rake db:create
rake db:migrate

now, assuming the server is still running from the previous chapter,
fire up your browser and go to http://localhost:3000/books/ and you
will be pleasantly surprised to find that you not only have a
functioning database, but also a minimal application that allows you
to add edit and destroy records in this database. Click on "new book"
to come to http://localhost:3000/books/new where you see a regular
data entry screen for the name, number and author of the book you wish
to enter into the database.

How do we use the database in our own programming? Next chapter. For now,
let me leave you with the output of the above commands, to help you
diagnose the fault if things go wrong.

>script/generate scaffold book name:string num:integer author:string
exists app/models/
exists app/controllers/
exists app/helpers/
create app/views/books
exists app/views/layouts/
exists test/functional/
exists test/unit/
exists public/stylesheets/
create app/views/books/index.html.erb
create app/views/books/show.html.erb
create app/views/books/new.html.erb
create app/views/books/edit.html.erb
create app/views/layouts/books.html.erb
identical public/stylesheets/scaffold.css
create app/controllers/books_controller.rb
create test/functional/books_controller_test.rb
create app/helpers/books_helper.rb
route map.resources :books
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/book.rb
create test/unit/book_test.rb
create test/fixtures/books.yml
exists db/migrate
create db/migrate/20090511140924_create_books.rb

>rake db:create
(in /home/user/ruby/code/test)
db/development.sqlite3 already exists

>rake db:migrate
(in /home/user/ruby/code/test)
== 20090511140924 CreateBooks: migrating ======================================
-- create_table(:books)
-> 0.2238s
== 20090511140924 CreateBooks: migrated (0.2250s) =============================

Again, just 3 lines of typing!