RadRailsでRailsアプリケーションことはじめ。part.1
参考本:http://ssl.ohmsha.co.jp/cgi-bin/menu.cgi?ISBN=4-274-06640-1
参考サイト:http://www.itmedia.co.jp/enterprise/articles/0703/12/news018.html
ユーザ管理機能をつくるとしよう・・
ユーザを一覧、追加、変更、削除の管理機能、およびユーザの抽出表示を行います。
データベースの作成
データベース設定ファイル(database.yml)の確認
Railsプロジェクトを生成したら、/config/database.ymlが以下のように生成されます。
/config/database.yml
development: adapter: mysql database: manager_development username: root password: host: localhost test: adapter: mysql database: manager_test username: root password: host: localhost production: adapter: mysql database: manager_production username: prod password: wibble host: localhost |
データベースの生成
■#1■MySQLでコマンド実行
Ruby Consoleから、
C:\InstantRails1.7\rails_apps>mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
mysql>create database manager_development;
mysql>grant all on manager_development.* to 'dave'@'localhost';
■#2■phpMyAdminから作成
http://localhost/mysql/へアクセスして、「新規データベースを作成する」
migrateでテーブル定義
-
- > #1 migrationファイルの生成
RadRailsのGeneratorビューを使用します。
Left Input | migration | Right Input | (例)CreateUsers |
---|---|---|---|
Type | Create | Option | なし。 |
すると、枠組みだけでスクリプトが空の状態で/db/migrate/001_create_users.rbが生成されます。
以下のように、編集します。
migration記述方法の参考サイト:http://akimichi.homeunix.net/hiki/rails/?cmd=view&p=migration&key=migration
/db/migrate/001_create_users.rb
class CreateUsers < ActiveRecord::Migration def self.up create_table(:users) do |t| t.column(:user_id, :integer) t.column(:name, :string) t.column(:gender, :string) t.column(:age, :integer) t.column(:birthday, :datetime) t.column(:phone, :string) t.column(:mobile_carrier, :string) end end def self.down drop_table(:users) end end
-
- > #2 テーブル生成
RadRailsのRake Tasksビューを使用します。
Left Input | db:migrate | Right Input | なし。 |
---|
Goすると、Consoleビューに以下の内容が表示されれば、生成完了です。
== CreateUsers: migrating ======================== -- create_table(:users) -> 0.0940s == CreateUsers: migrated (0.0940s) ===============
実行されると、/db/schema.rbファイルが生成されます。
# TASK : migrationでテーブルの更新をしたいときは、どうやってやるんだろう?