Madogiwa Blog

主に技術系の学習メモに使っていきます。

RubyonRails:RubyonRailsチュートリアル回答メモ(第1章)

Ruby on Rails チュートリアルの演習回答メモです。

第一章「ゼロからデプロイまで」

演習1

問1

リスト1.8のhelloアクションを書き換え、「Hello, world!」の代わりに「hola, mundo!」と表示されるようにしてみましょう。課外作業: Railsの表示では「非ASCII文字」もサポートされています。スペイン語特有の逆さ感嘆符「¡」を含む「¡Hola, mundo!」を表示してみましょう (図1.19)20 

回答

application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  def hello
      render text:"hola, mundo!"
  end
end
問2

リスト1.8のhelloアクションを複製して、第2のアクションgoodbyeを追加しましょう。このアクションは、「goodbye, world!」というテキストを表示します。リスト1.10のルーティングを編集して、ルートルーティングの割り当て先をhelloアクションからgoodbyeアクションに変更します (図1.20)。

回答

application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  def hello
      render text:"hola, mundo!"
  end

  def goodbye
      render text:"goodbye, world!!"
  end

end

routes.rb

Rails.application.routes.draw do
  root 'application#goodbye'
end

とりあえず、一章はここまで