form_for 방법에 대한 >>

14959 단어 Rails
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| %>↑ 이 줄만으로 데이터를 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>
상술한 내용을 하나하나 풀면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
상술한 표의 데이터를 뛰어넘어 보아라

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

좋은 웹페이지 즐겨찾기