Rails学習【ビュー2】

■テンプレートに値を表示する

テンプレートの利点はRuby側から(コントローラー側から)表示を操作できる。

<例>

#HelloControllerクラス(hello_controller.rb)を書き換える

class HelloController < ApplicationController
 
 def index
  @title = "View Sample"
  @msg = "コントローラーに用意した値です。"
 end
 
end
 
変数の前の@はインスタンス変数を意味する
クラスのインスタンス(クラスを元にして作られたオブジェクト)の中で常に値を保持している変数
 
・テンプレートを修正する
<例>
#index.html.erbを書き換える
<h1 class="display-4"><%= @title %></h1>
<p><%= @msg %></p>
 
<%= ○○ %>タグは、Rubyを実行して値を書き出す特殊なタグ
 
■リダイレクトとパラメータ送付
リダイレクト=あるアクションから別のアクションへ処理を転送すること
aのアクションにアクセスしたら必要な処理をしてbのアクションへ自動的に移動するなど
<例>
#ortherアクションを作り、そのままindexアクションにリダイレクト
(indexへ直接アクセスと、ortherからリダイレクトでindexへ直接アクセスした時で表示を変える)
#hello_controller.rbを書き換える
class HelloController < ApplicationController
 
 def index
  if params['msg'] != nil then
   @title = params['msg']
  else
   @title = 'index'
 end
 @msg = 'this is redirect sample...'
end

def orther
  redirect_to action: :index, params: {'msg': 'from orther page'}
end
 
end
 
・redirect_toメソッド
redirect_to action: アクション名, params:{.....ハッシュ.....}
actionというオプションでリダイレクト先でのアクションを指定
他のコントローラーのアクションに移動したい場合は、『controller: コントローラー名』という引数も用意できる
 
上記のindex側の処理はmsgというパラメータが送られてきたら@titleに決まった値を返すように記述
 
・routes.rbの修正
新しいアクションを作成したら、ルート情報を追加する
get 'hello/orther'
 
ルート情報の追加で、HelloControllerクラスのortherメソッドが利用できるようになる
 
実際にlocalhost:3000に【/hello】【/hello/orther】で接続テスト
#表示が変わる