Ruby on Rails

Ruby on Rails とは

スクリプト言語のRubyにより構築された、RESTfulなWebアプリケーション開発のためのフレームワーク。
MVC(Model-View-Controller)アーキテクチャをサポートしている。
特徴的なのは、モデル、ビュー、コントローラの雛形を自動生成する機能。
簡単なマスタメンテ画面であればテーブル作成するだけで、処理を自動生成できる。
但し、自動生成された画面に対しては、あんまり細かい事を言わないのが前提。

railsプロジェクトの作成

rails new -d mysql rails_example

※上記の場合、カレントディレクトリに rails_example ディレクトリが作成される

データベースとユーザの作成

mysql -u root -p
Enter password:
mysql> create database rails_example character set utf8;
Query OK, 1 row affected (0.01 sec)

mysql> create user rails_example@localhost identified by 'rails_example';
Query OK, 0 rows affected (0.01 sec)

mysql> GRANT ALL PRIVILEGES ON rails_example.* TO 'rails_example'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

mysql> quit

鍵の生成

bundle install
bundle exec rake secret

上記で表示された鍵を環境変数に設定しておく

export SECRET_KEY_BASE=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

以降は、実行前にプロジェクトのディレクトリに移動しておく

モデルの生成

rails generate model xxxxx

コントローラの作成

rails generate controller xxxxx

モデル、コントローラの生成

rails generate scaffold モデル名 列名1:データ型1 列名2:データ型2 ..

scaffoldの例

rails generate scaffold book isbn:string title:string price:integer

scaffoldの例(migrationをスキップする場合)

rails generate scaffold book isbn:string title:string price:integer --skip-migration

尚、scaffoldで指定できるデータ型は以下の通り。

シンボル説明対応するMySQLの型
:string文字列varchar(255)
:text長い文字列text
:integer整数int(11)
:float浮動小数float
:decimal厳密な精度の少数decimal
:datetime日時datetime
:timestampより細かい日時datetime
:time時間time
:date日付date
:binaryバイナリデータblob
:boolean真偽型tinyint(1)

DBのmigrate

rake db:migrate

DB(Mysql)への日本語データ登録でエラーになる場合

# データベースの文字コード変更
alter database DB名 character set utf8;

# テーブルの文字コード変更
alter table テーブル名 convert to character set utf8;

アクションの追加

※参照:http://d.hatena.ne.jp/zariganitosh/20080203/1202091772
(1) config/routes.rb に下記を追加

ActionController::Routing::Routes.draw do |map|
	.
	.
	.
	map.resources :employees, :collection => { :action1 => :get }
	.
	.
end
※employees はコントローラ名

(2) employees_controller.rb にメソッドを追加

定義済みアクションの確認

rake routes

rakeのタスク一覧の確認

rake -T

サーバの起動

rails server -e production

ActiveRecordの使い方(途中)

@employees = Employee.find(:all, :conditions => [ "name like ?", user_name])

テーブルデータの初期化(FIXTUREを利用)

test/fixtures/テーブル名.yml にテストデータを用意

one:
  name: EMP01
  dept_id: 1

two:
  name: EMP02
  dept_id: 1

data3:
  name: EMP03
  dept_id: 1

data4:
  name: EMP04
  dept_id: 1

data5:
  name: EMP05
  dept_id: 1

以下のようにスクリプトにする事も可能

<% 0.upto(9) do |n| %>
data<%= n %>:
  name: EMP<%= sprintf("%02d", n) %>
  dept_id: 1
<% end %>

データのロード

rake db:fixtures:load FIXTURES=employees


トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2016-05-08 (日) 03:13:13 (2903d)