Rails2.2でサンプルアプリを作ってみる(1)

Rails本といえば、「RailsによるアジャイルWebアプリケーション開発」が有名です。

RailsによるアジャイルWebアプリケーション開発 第2版
Dave Thomas David Heinemeier Hansson Leon Breedt Mike Clark Andreas Schwarz James Duncan Davidson Justin Gehtland
オーム社
売り上げランキング: 6743

が、Rails2に対応していないので、若干情報が古くて、最新版とは異なる部分があります。ということで、以下のチュートリアルをベースにdepotアプリを作ってみることにした。

Rails2に対応した「Agile Web Development with Rails, Third Edition」が販売されているので、購入するのもありかも。購入した。

使用しているバージョン

RubyRailsのバージョンは以下の通り。

$ ruby -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [i686-darwin9]
$ rails -v
Rails 2.2.2

Databaseは、MySQLを利用します。

$ mysql --version
mysql  Ver 14.14 Distrib 5.1.28-rc, for apple-darwin9.4.0 (i686) using readline 5.1

depotアプリケーションを作成する

$ rails depot -d mysql
      create  
      create  app/controllers
      create  app/helpers
      create  app/models
      create  app/views/layouts
      create  config/environments
      create  config/initializers
      create  config/locales
      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/performance
      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  test/performance/browsing_test.rb
      create  config/database.yml
      create  config/routes.rb
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/new_rails_defaults.rb
      create  config/locales/en.yml
      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/dbconsole
      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

これ以降、depot以下で操作を行っていきます。

$ cd depot/

Databaseの設定

config/database.yml を編集します。(username, passwordを変更します)

development:
adapter: mysql
encoding: utf8
database: depot_development
pool: 5
username: depot
password: depot
socket: /tmp/mysql.sock
データベースを作成する

この時点でデータベースを作成する必要はないようです。(後述しますが、rakeコマンドでデータベースを作成することができます)

今回、開発で利用するデータベース(depot_development)を作成しておきます。

root@localhost[(none)]> create database `depot_development` character set 'utf8';
Query OK, 1 row affected (0.00 sec)

データベース(depot_development)が作成されたことを確認しておきます。

root@localhost[(none)]> show databases like 'depot%';
+-------------------+
| Database (depot%) |
+-------------------+
| depot_development | 
+-------------------+
1 row in set (0.00 sec)
ユーザを作成する

接続ユーザをrootから専用のユーザに変更しているので、作成します。今回は、とりあえずナンも考えずに全権限付与しています。

root@localhost[(none)]> grant all on depot_development.* to 'depot'@'localhost' identified by 'depot';
Query OK, 0 rows affected (0.02 sec)

ユーザ(depot)が作成されたことを確認しておきます。

root@localhost[mysql]> select user, host from user where user = 'depot';
+-------+-----------+
| user  | host      |
+-------+-----------+
| depot | localhost | 
+-------+-----------+
1 row in set (0.00 sec)
MySQL Driverをインストールする

MySQL Driverをまだインストールしていない場合には、database.ymlに記載された指示にしたがってインストールします。

自分の環境は、Mac OS X (Leopard)なので、以下のようにしてインストールします。

$ sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config

Modelを作成する

$ script/generate scaffold Product title:string description:text image_url:string
      exists  app/models/
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/products
      exists  app/views/layouts/
      exists  test/functional/
      exists  test/unit/
      exists  public/stylesheets/
      create  app/views/products/index.html.erb
      create  app/views/products/show.html.erb
      create  app/views/products/new.html.erb
      create  app/views/products/edit.html.erb
      create  app/views/layouts/products.html.erb
      create  public/stylesheets/scaffold.css
      create  app/controllers/products_controller.rb
      create  test/functional/products_controller_test.rb
      create  app/helpers/products_helper.rb
       route  map.resources :products
  dependency  model
      exists    app/models/
      exists    test/unit/
      exists    test/fixtures/
      create    app/models/product.rb
      create    test/unit/product_test.rb
      create    test/fixtures/products.yml
      create    db/migrate
      create    db/migrate/20081209132148_create_products.rb

Databaseのマイグレーション用ファイル(db/migrate/20081209132148_create_products.rb)の中身を確認します。

class CreateProducts < ActiveRecord::Migration
  def self.up
    create_table :products do |t|
      t.string :title
      t.text :description
      t.string :image_url

      t.timestamps
    end
  end

  def self.down
    drop_table :products
  end
end

指定した列の定義が追加されていることが確認できます。rails 2.2では、マイグレーション用ファイルの名のシーケンス番号が日時になっていますね。

マイグレーションを適用する前に、データベースを作成します。rakeコマンドにdatabase.ymlの設定内容からデータベースの作成を行うことができます。(データベースを手動で作成する必要がなくなったので、便利ですね)

$ rake db:create
(in /Users/kouichi/Development/Ruby/depot)

念のため、データベース(depot_development)が作成されたことを確認しておきます。

depot@localhost[depot_development]> show databases like 'depot%';
+-------------------+
| Database (depot%) |
+-------------------+
| depot_development | 
+-------------------+
1 row in set (0.00 sec)

rakeコマンドには、便利なタスクが沢山が用意されているので、これをうまく使いこなしたいところです。以下のコマンドで利用可能なタスクの一覧が表示されるので、一度目を通しておくとよいです。

$ rake -T

やっと一通りの準備が整ったので、マイグレーションを適用します。

$ rake db:migrate
(in /Users/kouichi/Development/Ruby/depot)
==  CreateProducts: migrating =================================================
-- create_table(:products)
   -> 0.0734s
==  CreateProducts: migrated (0.0737s) ========================================

念のため、テーブル(products)が作成されたことを確認しておきます。

depot@localhost[depot_development]> show tables;
+-----------------------------+
| Tables_in_depot_development |
+-----------------------------+
| products                    | 
| schema_migrations           | 
+-----------------------------+
2 rows in set (0.01 sec)

Controllerを作成する

$ script/generate controller admin
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/admin
      exists  test/functional/
      create  app/controllers/admin_controller.rb
      create  test/functional/admin_controller_test.rb
      create  app/helpers/admin_helper.rb

確認する

WEBrickを起動します。

$ script/server 
=> Booting WEBrick...
=> Rails 2.2.2 application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with --help for options
[2008-12-15 07:16:32] INFO  WEBrick 1.3.1
[2008-12-15 07:16:32] INFO  ruby 1.8.7 (2008-08-11) [i686-darwin9]
[2008-12-15 07:16:32] INFO  WEBrick::HTTPServer#start: pid=1532 port=3000

http://localhost:3000/products へアクセスします。

まだデータは存在しないので、試しに登録してみます。


問題なく登録できました。

たったこれだけで、簡単に動く画面を作れました。

次回に続きます。
Rails2.2でサンプルアプリを作ってみる(2) - 積み重ねた日々へ続きます。