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 3 years have passed since last update.

#1.5 ユーザー編集機能

Last updated at Posted at 2021-10-06

#はじめに
自己学習復習シリーズの#1.5になります。
自己学習の為に記事作成しております。
この記事が誰か1人の役に立ったら幸いです。
今回はユーザー編集機能編です。

##ユーザー編集機能作成においてすべき事

  • users controllerにてeditアクション、updateアクションの作成&ストロングパラメーターの作成
  • routes.rbにてルーティングの作成
  • views/usersにedit.html.erbを作成し、編集フォームを作成
  • マイページや編集ページに遷移できるようにリンクを作成する

以上の4点を行えば、ユーザー編集機能の実装を終える事ができる。

今回は丁寧に、
(1)ルーティングの作成(editとupdate/routes.rbにて)。
(2)editアクションの記述(users controllerにて)。
(3)edit.html.erbにて編集フォームを作成。
(4)updateアクションの記述(users controllerにて)&ストロングパラメーターの作成。
(5)マイページと編集ページにリンク作成。
の順で説明していきます!

###(1)ルーティングの作成

routes.rb
resources :users, only: [:show, :edit, :update]

resourcesで作成しているので、そこにeditアクションとupdateアクションのルーティングを作成。

###(2)editアクションの記述

users_controller.rb
def edit
  @user = User.find(params[:id])
end

###(3)edit.html.erbにて編集フォームを作成

users/edit.html.erb
<h3><%= @user.name %>さんの編集画面</h3>

<%= form_with model:@user, local: true do |f| %>
<%= f.label :"名前" %>
<%= f.text_field :name %>

<%= f.label :"自己紹介" %>
<%= f.text_field :introduction %>

<%= f.label :"ステータス" %>
<%= f.text_field :status %>

<%= f.label :"画像" %>
<%= f.file_field :image %>

<%= f.submit '編集する' %>
<% end %>

form_withを用いて編集フォームを作成する。
ちなみにこの記述の状態だと、横並びのフォームになっている。
ーーーーーーー以下参考写真ーーーーーーーーーー
スクリーンショット 2021-10-07 2.12.17.png
ーーーーーーーーーーーーーーーーーーーーーーー

###(4)updateアクションの記述&ストロングパラメーターの作成

users_controller.rb
def update
  @user = User.find(params[:id])
  @user.update(user_params)
  redirect_to user_path(@user)
end

deviseによって作成されたuserなので、
user_controller.rbにcreateの時に作成されたストロングパラメーターが存在しない。
なので、private内にストロングパラメーターを記述する。

users_controller.rb
private

def user_params
  params.require(:user).permit(:name, :image, :introduction, :status)
end

###(5)マイページと編集ページにリンク作成
今のままだと編集ページに遷移できない&編集ページからは編集しないと戻れないので、、

users/show.html.erb
:
:
<%= link_to '編集する', edit_user_path(@user) %>
users/edit.html.erb
:
:
<%= link_to 'マイページへ戻る', user_path(@user) %>

#最後に
以上でユーザー編集機能の実装が終わりました。
ユーザー編集機能は慣れたら簡単だと思うので、復習を重ねて早く慣れましょう!!
今回も見てくださった方はありがとうございました!

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?