Ruby on RailsのDeviseではデフォルトでregistrations#editがありますが、こちらはemailやpasswordをeditするようにして、その他のnameなどはregistrations#profile_editを追加して、別ページでeditするように実装しました。
環境はこちらです
1 2 3 |
ruby 2.5.1 rails 5.1.6 devise 4.4.3 |
ルーティング
devise_scope に profile_edit と profile_update を追加します。
config/routes.rb
1 2 3 4 |
devise_scope :user do get 'profile_edit', to: 'users/registrations#profile_edit', as: 'profile_edit' patch 'profile_update', to: 'users/registrations#profile_update', as: 'profile_update' end |
コントローラー
忘れずaccount_update_paramsをセットします。
app/controllers/users/registrations_controller.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def profile_edit end def profile_update current_user.assign_attributes(account_update_params) if current_user.save redirect_to my_page_path, notice: 'プロフィールを更新しました' else render "profile_edit" end end protected def configure_account_update_params devise_parameter_sanitizer.permit(:account_update, keys: [:name]) end |
ビュー
app/views/devise/registrations/my_page.html.erb
1 |
<%= link_to 'プロフィール編集', profile_edit_path %> |
app/views/devise/registrations/profile_edit.html.erb
1 2 3 4 5 6 7 8 9 10 11 |
<%= form_for current_user, url: {action: 'profile_update'} do |f| %> <div class="field"> <%= f.label :name %><br /> <%= f.text_field :name %> </div> <div class="actions"> <%= f.submit "Update" %> </div> <% end %> |
以上です!😊