コントローラクラスの作成
Model - View - ControllerのうちControllerに対応するコントローラクラスを作成します。
$ cd data/railbook
$ rails generate controller hello
create app/controllers/hello_controller.rb
invoke erb
create app/views/hello
invoke test_unit
create test/functional/hello_controller_test.rb
invoke helper
create app/helpers/hello_helper.rb
invoke test_unit
create test/unit/helpers/hello_helper_test.rbこのコマンドにより、app/controllers配下にコントローラクラス本体が作成されます。コントローラクラスはコントローラ名 + _controller.rbという名称で作成されます。
Hello world!を表示するために、hello_controller.rbを以下のように修正します。
class HelloController < ApplicationController def index render :text => 'Hello world!' end end
リクエストを受けた際にコントローラが呼び出されるようにルーディングを設定します。
$ vim config/routes.rb match ':controller(/:action(/:id))(.:format)' #コメントアウトをはずす
サーバを起動し、端末からブラウザで「http://localhost:3000/hello/index」にアクセスし、「Hello world!」が表示できることを確認します。
$ rails server