Ruby on Railsの練習に、アクセスカウンタを作成してみる。
データベースの作成
MySQLを使用して、データベースとテーブルを作成する。
データベースを作成。
CREATE DATABASE `counter`;
テーブルを作成。
CREATE TABLE `counts` (
`id` INT NOT NULL AUTO_INCREMENT ,
`count` INT NOT NULL,
PRIMARY KEY ( `id` )
);
レコードを登録する。
INSERT INTO `counts` VALUES(0);
プロジェクトの作成
C:\railsディレクトリを作成する。
C:\railsディレクトリに移動して、次のコマンドを実行する。
rails counter
C:\rails\counter\config\database.ymlのdatabaseの項目をcounterに編集する。
development:
adapter: mysql
database: counter
host: localhost
username: root
password:
test:
adapter: mysql
database: counter
host: localhost
username: root
password:
production:
adapter: mysql
database: counter
host: localhost
username: root
password:
モデルとコントローラを作成する。
ruby script/generate model Count
ruby script/generate controller count
コーディング
C:\rails\counter\app\views\count\index.rhtml ファイルを作成する。
index.rhtmlでは、@countの値を表示する。
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja-JP" lang="ja-JP">
<head>
<title>カウンタ</title>
</head>
<body>
<h1>カウンタ</h1>
<p>
<%= @count %>
</p>
</body>
</html>
C:\rails\counter\app\controllers\count_controller.rb を開く。
countsテーブルの先頭のレコードを取得し、countフィールドの値に1を加算して、保存する。
@countの値は、index.rhtmlで表示する。
class CountController < ApplicationController
def index
count = Count.find(:first)
count.count += 1
count.save
@count = count.count
end
end
WEBrick サーバーを起動する。
ruby script/server
http://localhost:3000/count/にアクセスする。
リロードするたびに数字が増えたら成功。