
Rails makes it exceptionally easy to create a new table. In SMIG, my Stock Market Investment Game, I will need a table with stocks.
What do I want to know about each stock? Let's think of a specific stock, say Portland General Electric Company - the folks that bring me electricity. I want to know the trading symbol (POR), a description that tells me what stock this is (Portland General Electic), and the current price.
Eventually I'll need a way to get prices in real time, but initially I'll just store them in the database. I want to have a timestamp for the price in the database (so I will know how old it is and when to update the price). Maybe I will need to know what exchange (NYSE, NASDAQ, etc) the stock trades on. Also, I should give players a way to find out more about a stock, so I'll include a URL to more information about the stock.
There are only a limited number of stock exchanges, so I will eventually want to have a table listing the exchanges. For now, I'll just have an integer that will be an index into the Exchange table.
The following command creates a database table entry for the Stocks table:
$ script/generate scaffold stock symbol:string description:string exchange_id:string price:float pricestamp:timestamp url:string
Every time I make additions to the database, I also need to migrate up to the latest version of the database.
$ rake db:migrate
Scaffold does a lot more than just create the database table for Stocks. It also creates app/controllers/stocks_controllers.rb file and app/views/stocks directory with initial scaffold code to list, view, create, update and delete stocks!
I can access this initial code by browsing to http://localhost:3000/stocks.
Initially the list will be empty, but there is a "New Stock" link at the bottom. Clicking on that link gives me the create new stock window, shown above.
Later on I might forget the names and types of the fields I created. I could go to MySQL and look at the fields in the table. Or, I could go to smig/db/migrate and find 20090929235716_create_stocks.rb file. There I will see:
class CreateStocks < ActiveRecord::Migration
def self.up
create_table :stocks do |t|
t.string :symbol
t.string :description
t.integer :exchange_id
t.float :price
t.timestamp :pricestamp
t.string :url
t.timestamps
end
end
def self.down
drop_table :stocks
end
end