0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

form_forメソッド作成されるhtmlについて

Last updated at Posted at 2019-07-11
items_controller.rb
class ItemsController < ApplicationController

	def index
		# itemsテーブルの中身すべてを@itemsインスタンス変数に代入
		@items = Item.all
	end

	# 新しいユーザーを登録する画面に移動
	def new
		# itemsテーブルに紐付いたインスタンスを作成し、インスタンス変数に代入
		@item = Item.new
	end

	# new.htmlからpostで送信されたデータを受け取る
	def create
		# binding.pry
		Item.create(name: item_params[:name], price: item_params[:price])
	end

		# Strong Parameter
		private
		def item_params
			params.require(:item).permit(:name, :price)
		end

end
new.html.erb
<%= form_for @item, method: :post do |f| %>
  <h1>ご購入商品の情報を入力</h1>
  <p>商品名:<%= f.text_field :name %></p>
  <p>値段:<%= f.text_field :price %></p>
  <input type="submit" value="SENT">
<% end %>

上記のようなcontrollerファイルと、erbファイルがあったとする。

疑問に思ったこと

<%= form_for @item, method: :post do |f| %>
↑この1行だけでitems_controller.rbcreateアクションにデータを飛ばせるって謎だな・・・(腑に落ちない)

人生逆転サロンで質問してみると、どうやらform_forメソッドが略されている模様。

↓略されているバージョン

new.html.erb
<%= form_for @item, method: :post do |f| %>
  <h1>ご購入商品の情報を入力</h1>
  <p>商品名:<%= f.text_field :name %></p>
  <p>値段:<%= f.text_field :price %></p>
  <input type="submit" value="SENT">
<% end %>

↓略されていないバージョン

new.html.erb
<%= form_for @item,
             as: :item,
             url: items_path,
             html: { class: "new_item", id: "new_item" } do |f| %>
  <h1>ご購入商品の情報を入力</h1>
  <p>商品名:<%= f.text_field :name %></p>
  <p>値段:<%= f.text_field :price %></p>
  <input type="submit" value="SENT">
<% end %>

略されていないバージョンで、実際にどういうHTMLが生成されているか見てみよう↓
(略されているバージョンでも同じHTMLが作成されることは確認済み)

ブラウザ上で作成されたHTML
<form class="new_item" id="new_item" action="/items" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="gO1KEJfKfbzGU8aLVT6KnfErKHBdoTwXU97YPBXa/+Qm+XK+MTTOZVFJJ9AMINdRMaEIpq/oop1vPQL/ODMGIg==">
  <h1>ご購入商品の情報を入力</h1>
  <p>商品名:<input type="text" name="item[name]" id="item_name"></p>
  <p>値段:<input type="text" name="item[price]" id="item_price"></p>
  <input type="submit" value="SENT">
</form>

上記を1つずつ紐解いていくと・・・

url: items_pathaction="/items"

html: { class: "new_item", id: "new_item" }class="new_item" id="new_item"

f.text_field :name<input type="text" name="item[name]" id="item_name">

f.text_field :price<input type="text" name="item[price]" id="item_price">

「ん???じゃあ、as: :itemは何をしているの・・・?」と新たな疑問が浮かんだ
調べるとas:form_forのオプションであり、これを指定することでparamsのハッシュのキーを上書きできるのだ

as: :kotonohaに修正↓

<%= form_for @item,
             as: :kotonoha,
             url: items_path,
             html: { class: "new_item", id: "new_item" } do |f| %>
  <h1>ご購入商品の情報を入力</h1>
  <p>商品名:<%= f.text_field :name %></p>
  <p>値段:<%= f.text_field :price %></p>
  <input type="submit" value="SENT">
<% end %>

params.require(:kotonoha)に修正↓

class ItemsController < ApplicationController

	def index
		# itemsテーブルの中身すべてを@itemsインスタンス変数に代入
		@items = Item.all
	end

	# 新しいユーザーを登録する画面に移動
	def new
		# itemsテーブルに紐付いたインスタンスを作成し、インスタンス変数に代入
		@item = Item.new
	end

	# new.htmlからpostで送信されたデータを受け取る
	def create
		# binding.pry
		Item.create(name: item_params[:name], price: item_params[:price])
	end

		# Strong Parameter
		private
		def item_params
			params.require(:kotonoha).permit(:name, :price)
		end

end

上記でフォームのデータを飛ばしてみる
スクリーンショット 2019-07-11 19.28.06.png

binding.pryで中身を見ると下記のようにデータを取り出せる

[1] pry(#<ItemsController>)> params
=> <ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"Fxno0T/Z44CIOmfkHAdxph2I9yHZUFtDI2Nsj5SC4X9aDep+aAgPAQeVJJJ+v5S3ePjpmW5t0SVN7NgkLcEGCw==", "kotonoha"=>{"name"=>"kotonoha", "price"=>"11111"}, "controller"=>"items", "action"=>"create"} permitted: false>
[2] pry(#<ItemsController>)> params[:kotonoha]
=> <ActionController::Parameters {"name"=>"kotonoha", "price"=>"11111"} permitted: false>
[3] pry(#<ItemsController>)> params[:kotonoha][:name]
=> "kotonoha"

これは面白い・・・(むずかしいですな〜〜〜!)

参考記事↓
https://techracho.bpsinc.jp/hachi8833/2017_04_20/38378

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?