Rails

form_tagをform_withで書き直す場合

More than 1 year has passed since last update.

form_tagでの書き方

form_tagでこう書くと

<%= form_tag({ controller: :items, action: :search }, id: :header_search_form, class: :search_form) do %>
    <div class="icon_search_wrapper">
      <i class="icon-search" aria-hidden="true"></i>
    </div>
    <div class="search_input_wrapper">
      <%= text_field_tag :header_search, nil, {placeholder: :Search, class: :search_input, autocomplete: :off, maxlength: 250, 'aria-label': :Search} %>
    </div>
<% end %>

HTMLになると↓

<form id="header_search_form" class="search_form" action="/items/search" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="ncYZH6RyeLPyWxFh4l9dNWV9XLweL99YIRspU+W8v4ifHJp1RFK7AcQST3M3KTCAm2QH26Eyh+sSTA++ZidiCQ==">
    <div class="icon_search_wrapper">
      <i class="icon-search" aria-hidden="true"></i>
    </div>
    <div class="search_input_wrapper">
      <input type="text" name="header_search" id="header_search" placeholder="Search" class="search_input" autocomplete="off" maxlength="250" aria-label="Search">
    </div>
</form>

form_withでの書き方

上記のform_tagと同じような処理をform_withで書くとこうなる。

<%= form_with(model: :items, scope: :post, url: items_search_path, id: :header_search_form, class: :search_form) do %>
    <div class="icon_search_wrapper">
      <i class="icon-search" aria-hidden="true"></i>
    </div>
    <div class="search_input_wrapper">
      <%= text_field_tag :header_search, nil, {placeholder: :Search, class: :search_input, autocomplete: :off, maxlength: 250, 'aria-label': :Search} %>
    </div>
<% end %>

だが、これはHTMLになると↓

<form id="header_search_form" class="search_form" action="/items/search" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="Gb4Ol3trq6vFCosVD2eTACr7OWtGhfI/L54+pQ7j1D1OSid2cfAz9Dk5ZcX1wVlz0BwBhdRTB7ZZ8lBICRCjpg==" />
    <div class="icon_search_wrapper">
      <i class="icon-search" aria-hidden="true"></i>
    </div>
    <div class="search_input_wrapper">
      <input type="text" name="header_search" id="header_search" placeholder="Search" class="search_input" autocomplete="off" maxlength="250" aria-label="Search" />
    </div>
</form>

となり、data-remote="true"が追加され、ブラウザ側の制御によるフォーム送信が行われなくなっている。

ここも同じにしたい場合は、:localオプションをfalseで指定すれば良い。

<%= form_with(model: :items, scope: :post, url: items_search_path, local: :false, id: :header_search_form, class: :search_form) do %>
    <div class="icon_search_wrapper">
      <i class="icon-search" aria-hidden="true"></i>
    </div>
    <div class="search_input_wrapper">
      <%= text_field_tag :header_search, nil, {placeholder: :Search, class: :search_input, autocomplete: :off, maxlength: 250, 'aria-label': :Search} %>
    </div>
<% end %>

参考