LoginSignup
3
3

More than 1 year has passed since last update.

【Rails】deviseの編集ページのform_forをform_withに書き換えるコード例

Last updated at Posted at 2021-03-10

※2022年から技術系の記事は個人ブログに投稿しております。ぜひこちらもご覧ください→yamaday0u Blog

Railsのgemであるdeviseであらかじめ用意されているビューを使ったとき、ユーザー登録のためのヘルパーメソッドはform_forによって実装されています。

Rails5.1以降、form_forではなくform_withの利用を推奨されているので、できるだけform_withへ書き換えたいところです。

そこで今回はapp/views/devise/registrations/edit.html.erbについて、form_forからform_withに置き換えてみます。

書き換え前

app/views/devise/registrations/edit.html.erb
 <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>

書き換え後

app/views/devise/registrations/edit.html.erb
<%= form_with model: @user, url: user_registration_path, local: true do |f| %>

model: @userでデータベースのusersテーブルに保存されているユーザー情報をあらかじめ入力フォームに入れてくれます。

ちなみに以下のように2行目以降の各フォームの値に@user.カラム名の記述をしなくてもデータが入ります。

app/views/devise/registrations/edit.html.erb
<%= form_with model: @user, url: user_registration_path, local: true do |f| %>
  <%= render "devise/shared/error_messages", resource: resource %>

  <div class="form-wrap">
  <div class="form-group">
    <%= f.label :name %><br />
    <%= f.text_field :name, autofocus: true %>
  </div>

  <div class="form-group">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
  </div>

  <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
    <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
  <% end %>

  <div class="form-group">
    <%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
    <%= f.password_field :password, autocomplete: "new-password" %>
    <% if @minimum_password_length %>
      <br />
      <em><%= @minimum_password_length %> characters minimum</em>
    <% end %>
  </div>

  <div class="form-group">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
  </div>

  <div class="form-group">
    <%= f.label :identity %><br />
    <%= f.text_field :identity, autocomplete: "current-password" %>
  </div>

  <div class="form-group">
    <%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
    <%= f.password_field :current_password, autocomplete: "current-password" %>
  </div>

  <div class="actions">
    <%= f.submit "Update", class: "sign-up-btn" %>
  </div>
  </div><%# end of "form-wrap" %>
<% end %>

実際のビュー

スクリーンショット 2021-03-11 1.39.05.png

参考資料

フォーム(form) | Railsドキュメント

3
3
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
3
3