dshimizu/blog

アルファ版

Mac OS X 10.7.5 (LION) でRails3のscaffoldを使った簡易アプリケーションの構築

はじめに

前回までで、Apacheと連携させたRuby on Rails環境の構築が完了しました。
今回は、開発環境の最終段階として、構築したRuby on Rails環境をBDと連携させて簡易なアプリケーションを動作させてみました。
Railsで利用する標準DBはSQLiteになってますが、他にもMySQLPostgreSQLを使用することができます。
ここではMySQLを使ったRuby on Rails環境の構築のため、MySQLをインストールし、Railsとの接続を試してみましたのでここにまとめ、記載致します。

事前準備(MySQLの設定)

Railsアプリケーションで利用するデータベースを作成しておきます。 ここではscaffoldapp_developmentという名前のデータベースを作成します。


mysql> mysql -u root -p
mysql> create database scaffoldapp_development default character set utf8;
Query OK, 1 row affected (0.00 sec)
mysql> show databases;
+---------------------+
| Database |
+---------------------+
| information_schema |
| mysql |
| performance_schema |
| test |
| scaffoldapp_development |
+---------------------+
5 rows in set (0.01 sec)

Railsからデータベースへ接続するためのユーザを作成します。 ここではrailsという名前のユーザを作成し、railsユーザのパスワードをrailsとしています。


mysql> grant all on scaffoldapp_development.* to 'rails'@'localhost';
Query OK, 0 rows affected (0.01 sec)
mysql> set password for 'rails'@'localhost' = password('rails');
Query OK, 0 rows affected (0.00 sec)
scaffoldによるRailsアプリケーションの作成

前回設定したApacheのドキュメントルート(/Users/xxxxx(ユーザ名)/www/)へ移動し、Railsアプリケーションを作成します。-dオプション(データベース指定用のオプション)にmysqlを指定します。


% cd /Users/xxxxx(ユーザ名)/www
% rails new scaffoldapp -d mysql

scaffoldapp フォルダへ移動し、以下のコマンドを実行します。


% cd /Users/xxxxx(ユーザ名)/www/scaffoldapp
% rails g scaffold item name:string phone:string mail:string
invoke active_record
create db/migrate/20130120105422_create_items.rb
create app/models/item.rb
invoke test_unit
create test/unit/item_test.rb
create test/fixtures/items.yml
invoke resource_route
route resources :items
invoke scaffold_controller
create app/controllers/items_controller.rb
invoke erb
create app/views/items
create app/views/items/index.html.erb
create app/views/items/edit.html.erb
create app/views/items/show.html.erb
create app/views/items/new.html.erb
create app/views/items/_form.html.erb
invoke test_unit
create test/functional/items_controller_test.rb
invoke helper
create app/helpers/items_helper.rb
invoke test_unit
create test/unit/helpers/items_helper_test.rb
invoke assets
invoke coffee
create app/assets/javascripts/items.js.coffee
invoke scss
create app/assets/stylesheets/items.css.scss
invoke scss
create app/assets/stylesheets/scaffolds.css.scss

ここで生成されるファイルは以下のようなものです。


testapp … アプリケーションのルートディレクト
- app … MVCに関わるアプリケーションの中心的なコード
- asset … 画像、CSSJavaScript
- controllers … コントローラークラス
- items_controller.rb … コントローラクラス
- helpers … ヘルパーモジュール(ビュー用のヘルパーメソッド)
- items_helper.rb … ビューヘルパー
- mailers … メール用のコントローラー
- models … モデルクラス
- items.rb … モデルクラス
- views … テンプレート類
- items
- edit.html.erb … 編集画面
- index.html.erb … 一覧画面
- new.html.erb … 新規登録画面
- show.html.erb … 詳細画面
- _from.html.erb … 部分テンプレート
- config … 設定ファイル類
- environments … 開発、テスト、本番運用といった環境ごとの設定
- initializers … アプリケーション起動時に実行したいファイル
- locales … 国際化に関するリソース
- db … データベースに関するファイル
- migrate
- YYYYMMDDhhmmss_create_items.rb … DBマイグレーションファイル
- doc … rdocなどのドキュメント
- lib … アプリケーションが使うライブラリコード全般
- log … アプリケーションが出力するログ
- public … Webの静的なコンテンツ
- script … ユーティリティースクリプト
- test … Railsのデフォルトの自動テストに関するファイル
- fixtures
- items.yml … テストデータ用Fixtureファイル
- functional
- items_controller_test.rb … ファンクショナルテスト用ファイル
- integration
- performance
- unit
- item_test.rb … ユニットテスト用ファイル
- helper
- item_helper_test.rb … ヘルパークラスのユニットファイル
- tmp … 一時ファイル
- vendor … アプリケーション外部に由来するコード

database.xmlファイルにrailsから接続するためのmysqlのユーザ/パスワード、接続先データベース名を記載します。


% cd config
% vim database.yml
### 修正
development:
adapter: mysql2
encoding: utf8
reconnect: false
database: scaffoldapp_development <-MySQLの設定環境に合わせて記載
pool: 5
username: rails <-MySQLの設定環境に合わせて記載
password: rails <-MySQLの設定環境に合わせて記載
socket: /tmp/mysql.sock

Rake(Rubyのビルドツール)を用いてデータベースのマイグレーションを行います。
以下のコマンドを実行することで、MySQLデータベースに必要なテーブルを自動で作成できます。


% rake db:migrate
== CreateItems: migrating ====================================================
-- create_table(:items)
-> 0.0118s
== CreateItems: migrated (0.0119s) ===========================================

マイグレーションの状態を確認するには以下のように実行します。


% rake db:migrate:status
(in /Users/shimizu/www/scaffoldapp)

database: testapp_development

Status Migration ID Migration Name
--------------------------------------------------
up 20130120105422 Create items

MySQLにログインしてテーブルが作成されていることを確認してみます。


% mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 14
Server version: 5.5.29 Source distribution

Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>
mysql> use scaffoldapp_development
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql>
mysql> show tables;
+-------------------------------+
| Tables_in_scaffoldapp_development |
+-------------------------------+
| items |
| schema_migrations |
+-------------------------------+
2 rows in set (0.00 sec)

動作確認

127.0.0.1(localhost)へのhttpアクセスでRailsアプリケーションの画面が表示されるはずです。

http://127.0.0.1/scaffoldapp/public/items

少し操作してみます。テキストボックスに適当に入力して"Create Item"を押下します。
以下のように表示されます。

おわりに

以上で、MySQLを使ったRailsアプリケーションの環境が構築できました。

参考

今回の作業にあたり、以下の記事を参考にさせていただきました。