RailsでHello, world!を表示してみる

CentOSにPassenger/Ruby2.0/Rails4.0をインストールしてみる(rbenv版)の続き

RailsでHello, world!を表示してみる。

とりあえずHello, world!を表示してみる

railsのコマンドでコントローラを作成する。
今回はsampleという名前のコントローラにする。

$ rails generate controller sample
      create  app/controllers/sample_controller.rb
      invoke  erb
      create    app/views/sample
      invoke  test_unit
      create    test/controllers/sample_controller_test.rb
      invoke  helper
      create    app/helpers/sample_helper.rb
      invoke    test_unit
      create      test/helpers/sample_helper_test.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/sample.js.coffee
      invoke    scss
      create      app/assets/stylesheets/sample.css.scss
間違ってコントローラを作成した場合は、destroyで削除できます。
$ rails destroy controller sample

indexのアクションを作成する。

$ vi app/controllers/sample_controller.rb
class SampleController < ApplicationController
  def index
    render :text => "Hello, world!"
  end
end
「render :text」を指定すると、ビューが無くても、直接文字列が表示されます。
【参考】
render - リファレンス - Railsドキュメント
http://railsdoc.com/references/render

routes.rbを編集して、rootのところを下記のように修正する。

$ vi config/routes.rb
Sample::Application.routes.draw do
  ・・・
  # root 'welcome#index'
  root 'sample#index'
  ・・・
end

これで、下記のURLにアクセスすると「Hello, world!」が表示される。
http://サーバーのアドレス/

ViewでHello, world!を表示する

indexアクションのrender部分を削除し、indexアクションの中身を空にする。

$ vi app/controllers/sample_controller.rb
class SampleController < ApplicationController
  def index
  end
end

viewを作成する。

$ vi app/views/sample/index.html.erb
<h1>Hello, world!</h1>

http://サーバーのアドレス/
にアクセスすると、「Hello, world!」が表示される。