Ruby on Rails入門

ビューとコントローラ
やりたいこと
http://localhost:3000/hello/input にアクセ
ス
 名前を入力すると
 http://localhost:3000/hello/greeting で挨
拶してくれる
 データベースは利用しない

ビューとコントローラ
2
Railsのプロジェクト作成

以下のコマンドを入力して、helloというプロ
ジェクトを作成する
– andoh$ rails hello
ビューとコントローラ
3
コントローラの作成

hello ディレクトリに移動して、次のコマンド
を実行
– andoh$ ruby script/generate controller hello
input greeting

hello というコントローラと、input と greeting
というアクションを作成する。
ビューとコントローラ
4
生成された
app/controllers/hello_controller.rb
# コントローラ名は Hello + Controller
# ApplicationControllerを継承
class HelloController < ApplicationController
#inputアクション
def input
end
# greetingアクション
def greeting
end
end
ビューとコントローラ
5
URLとコントローラ
http://localhost:3000/hello/input
 http://localhost:3000/hello/greeting
 hello がコントローラ名
 inputとgreetingがアクション名

# コントローラ名は Hello + Controller
class HelloController < ApplicationController
#inputアクション
def input
end
# greetingアクション
def greeting
end
end
ビューとコントローラ
6
Railsアプリケーションの動作
1.
2.
3.
4.
5.
DispatcherがRequestを受け取る (HTTP)
コントローラとアクションを決定
コントローラ中のアクションが処理
ビューを処理
ブラウザにResponseを返す (HTTP)
ビューとコントローラ
7
Railsのビュー

eRubyフォーマットの実装であるERBが担
当
– eRubyはRubyのテンプレートエンジン

“(アクション名).rhtml” というファイル名
ビューとコントローラ
8
サーバを起動する
ruby script/server コマンドを実行
 WEBrick という Rails組み込みのWebサー
バが起動される

– デフォルトでは3000ポートで起動

アクションに対応したビューが表示される
– http://localhost:3000/hello/input
– http://localhost:3000/hello/greeting
ビューとコントローラ
9
app/views/hello/input.rhtmlに
フォームを追加
<h1>お名前を入力</h1>
ボタンを押したらgreeting
アクションに移る
<% form_tag :action => :greeting do %>
<%= text_field :input, :name %>
<%= submit_tag 'OK' %>
<% end %>
text_filed object_name, method, options = {}
ビューとコントローラ
10
app/controllers/hello_controller.rb
を編集
# @params はパラメータ情報を管理するため
# のインスタンス変数
# アクションで定義されたインスタンス変数は
# ビューで利用できる
def greeting
@str = @params.inspect
end
ビューとコントローラ
11
app/views/hello/greeting.rhtml
を編集
<%= @str %>
greetingアクションの@str変数の値を
表示
ビューとコントローラ
12
実行
input のテキストフィールドに「安藤友晴」と入力し
てボタンを押すと
 greeting で次の文字列が表示される

{ "commit"=>"OK", "action"=>"greeting",
"controller"=>"hello",
"input"=>{"name"=>"安藤友晴"} }

これがパラメータの情報になる
ビューとコントローラ
13
greetingで名前を表示する

app/controllers/hello_controller.rb を編集
def greeting
@name = @params[:input][:name]
end

app/views/hello/greeting.rhtmlを編集
<h1>ごあいさつ</h1>
<%= "こんにちは、#{@name}さん" %>
<% form_tag :action => :input do %>
<%= submit_tag '戻る' %>
<% end %>
ビューとコントローラ
14
config/routes.rb
ActionController::Routing::Routes.draw do |map|
map.connect ':controller/service.wsdl', :action => 'wsdl'
map.connect ':controller/:action/:id.:format'
map.connect ':controller/:action/:id'
end
#
#
#
#
#
map.connect ‘:controller/:action/:id’ に着目
URLの形式が <コントローラ名>/<アクション名>/<id> で
あることを示している
このファイルに
map.connect 'h/:action/:id', :controller => 'hello'
# を追加したらどのように動くだろうか?
ビューとコントローラ
15