前回(RubyをApacheで動かす)の続きです。
RubyGemsでRuby on Railsをインストールします。
gem install rails -y
これを実行すれば、railsコマンド使えるようになります。
試しに、これを実行してみます。
rails -v
Railsのバージョンが確認できるはずです。
Railsはデフォルトでsqlite3を使うので、これに必要なWindows用バイナリとDLLを拾ってきましょう。

sqlite3.exe
sqlite.dllをパスの通ったディレクトリ(C:\ruby\bin)にコピーしてください。
次にRDBMSを利用するためのライブラリをインストールします。
gem install sqlite3-ruby
Windows用の sqlite3-ruby(mswin32)を選択します。
これでとりあえず完了!
では、早速Hello Worldアプリケーションに取り掛かることにしましょう。
プロジェクトの作成
rails address_book
コントローラを作成します。
ruby script\generate controller welcome
\address_book\app\controllers\welcome\hello
を以下のように編集。
class WelcomeController < ApplicationController
def hello
@hello = "hello world!" + Time.now.strftime(" at %Y-%m-%d %H:%M:%S")
render :action => :hello
end
end
\address_book\app\views\welcome\hello.rhtml
にHTMLテンプレートを用意する。
<html>
<p><%=h @hello %></p>
</html>
サーバーを起動させてみる。
ruby script/server

http://localhost:3000/welcome/hello/
にアクセス。うまくいった!

次に、テーブルの作成とコードを自動生成してみます。
ruby script\generate scaffold friend name:string nickname:string birthday:date
migrationファイルが一緒に生成されます。
NOT NULL制約、サイズ制限などを追加する場合は修正。
class CreateFriends < ActiveRecord::Migration
def self.up
create_table :friends do |t|
t.string :name
t.string :nickname
t.date :birthday
t.timestamps
end
end
def self.down
drop_table :friends
end
end
migrate。
rake db:migrate
(in C:/Program Files/Apache Group/Apache2/htdocs/ruby/address_book)
== 20080704044225 CreateFriends: migrating ====================================
-- create_table(:friends)
-> 0.0780s
== 20080704044225 CreateFriends: migrated (0.0780s) ===========================
きちんとテーブルが生成されたか調べてみる。
sqlite3 db\development.sqlite3
出力結果
pment.sqlite3
SQLite version 3.5.9
Enter ".help" for instructions
sqlite> .tables
friends schema_migrations
sqlite> .schema
CREATE TABLE "friends" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name"varchar(255) DEFAULT NULL NULL, "nickname" varchar(255) DEFAULT NULL NULL, "birthday" date DEFAULT NULL NULL, "created_at" datetime DEFAULT NULL NULL, "updated_at" datetime DEFAULT NULL NULL);
CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL);
CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version"
);
サーバーを起動させてみる。
ruby script/server
http://localhost:3000/friend/
管理画面ができあがってる!?


