プロフィール編集機能の実装

profiles_controllerの作成

rails g controller profiles

 

profiles_controllerにアクションを追加する

class ProfilesController < ApplicationController
before_action :set_user, only: %i[edit update]
 
def edit; end

def update
if @user.update(user_params)
redirect_to profile_path
flash[:success] = '更新しました'
else
flash.now[:danger] = '更新できませんでした'
render :edit
end
end

def show; end

private

def set_user
@user = User.find(current_user.id)
end

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

 

ビューの設定


<div class="container">
<%= form_with model: @user, url: profiles_path, local: true do |f| %>
<div class="form-group">
<%= f.label :email%>
<%= f.text_field :email, class:'form-control'%>
</div>
<div class="form-group">
<%= f.label :nickname%>
<%= f.text_field :nickname, class:'form-control'%>
</div>
<%= f.submit '編集', class:'btn btn-primary'%>
<% end %>
</div>

 

ルーティングの設定

resource :profiles, only: %i[show edit update]