Rails3.2 でコントローラから Hello world! を表示する
前回 のつづき。
Ruby on Rails 3 アプリケーションプログラミング
- 作者: 山田祥寛
- 出版社/メーカー: 技術評論社
- 発売日: 2011/05/12
- メディア: 大型本
- 購入: 24人 クリック: 634回
- この商品を含むブログ (35件) を見る
まずは Rails プロジェクトの作成から。
$ mkdir ~/rails; cd ~/rails
$ rails new hellorails
次に rails generate コマンドを使ってコントローラクラスを作成する。
$ 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
invoke assets
invoke coffee
create app/assets/javascripts/hello.js.coffee
invoke scss
create app/assets/stylesheets/hello.css.scss
ずらっとファイルが生成される。
ちなみに、rails generate で自動生成したファイルは、rails destroy コマンドでまとめて削除することができる。
$ rails destroy controller hello
Hello world! を表示するために、コントローラクラスファイルの hello_controller.rb を編集する。
class HelloController < ApplicationController def index render :text => 'Hello world!' end end
日本語も表示したいぜって場合には、ファイルの行頭に coding: utf-8
を追記。
# coding: utf-8 class HelloController < ApplicationController def index render :text => 'こんにちは、世界!' end end
さらに、サーバがリクエストを受けた際に作成したコントローラを呼び出すよう、ルーティングの設定を行う。
$ vim config/routes.rb
# This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. match ':controller(/:action(/:id))(.:format)'
最後に、サーバを起動して、http://localhost:3000/hello/index にアクセスし、Hello world!
の文字が表示されていることを確認する。
$ rails server