LoginSignup
0
0

More than 3 years have passed since last update.

TECH CAMP学習 個人アプリ作成③

Posted at

ユーザー情報編集機能の追加

まずはターミナルにて以下のコードを入力します。

terminal.
$ rails g controller users

続いてルーティングで下記を入力します。

routes.rb
 devise_for :users
 root "photos#index"
 resources :users, only: [:edit, :update]

resourcesの意味は日本語では資源をいう意味で、usersの中で編集と更新の機能を利用するという解釈でよいと思います。

続いてコントローラーを編集します。

users_controller.rb
def edit
end

def update
   if current_user.update(user_params)
      redirect_to root_path
   else
      render :edit
   end
end

private

def user_params
   params.require(:user).permit(:name, :email)
end

①current_userはdeviseのヘルパーメソッドで、ログイン中のユーザー情報を取得できます。
②redirect_toは本来受け取ってるパスとは別のパスへ転送します。上記ではroot_pathに転送するということです。
③上記が失敗した場合、renderはeditを呼び出します。
④privateはプライベートメソッドで、クラス外から呼び出すことのできないメソッドです。
メリットしては
・classの外部から呼び出されたら困るメソッドを隔離
・可読性、classの外部から呼び出されたメソッドを探すときにprivate以下の部分は目を通さなくてよくなる。
⑤user_params以下はストロングパラメーターで、指定したキーを持つパラメーターのみを受け取るようにするものです。
⑥ストロングパラメーターの中でuserを要求(require)して:name,:emailの許可(permit)を得る。詳細を確認するにはupdateの直後にbinding.pryを使用する。

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