Rails学習【ビュー3】

■フォームの送信

パラメータによる値の送信はプログラム内からアクセスする場合には便利だが、

ユーザーから入力してもらう場合はフォームを利用するといい。

<例>

#index.html.erbを書き換える

<h1 class="display-4"><%= @title %></h1>
<p><%= @msg %></p>
<form method="POST" action="/hello/index">
<input type="text" class="form-control"
name="input1" value="<%= @value %>">
<input type="submit" class="btn btn-primary">
</form>
 
シンプルな入力フィールドと送信ボタン
送信先は/helloにPOST送信する形
それぞれのclassに設定した"form-control"と"btn btn-primaryはBootstrapのクラス。
 
GET方式=誰がどこからアクセスしても同じ表示
POST方式=その時一度限りのアクセスによる表示
 
・GETとPOSTで処理を分ける
先述のindex.html.erbは/helloで表示したフォームをそのまま/helloにPOST送信している。
(GET)なのか、(POST)なのかをチェックして処理を分けていく
<例>
#HelloControlクラスを修正する
class HelloController < ApplicationController
 
 def index
  if request.post? then
   @title = 'Result'
   @msg = 'you typed: ' + params['input1'] + '.'
   @value = params['input1']
  else
   @title = 'Index'
   @msg = 'type text...'
   @value = ''
  end
 end

end
 
requestはwebブラウザからサーバーへ送られた情報をまとめたオブジェクト
どういう形でアクセスされたのか細かい情報が入っている
post?はPOST送信したかを示すメソッド
この結果を元に処理を分けていく
 
Railsではクエリーパラメーターでもフォーム送信でも送られてきた値は全てparamsに入っている
 
・ルーティング設定
<例>
#routes.rbを書き換える
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
get 'hello/index'
get 'hello', to: 'hello#index'
get 'hello/orther'
post 'hello', to: 'hello#index'
post 'hello/index'
end
 
CSRF対策
外部からの攻撃の対策。フォームの送信はフォームそのものから送信しなくても処理できてしまうが、Railsにはフォーム利用に特別な機能を設けている
<例>CSRF対策を通過させる
#hello_controller.rbを書き換える
class HelloController < ApplicationController
protect_from_forgery
 
def index
if request.post? then
@title = 'Result'
@msg = 'you typed: ' + params['input1'] + '.'
@value = params['input1']
else
@title = 'Index'
@msg = 'type text...'
@value = ''
end
end

end