1
0

More than 1 year has passed since last update.

ユーザー情報の編集機能

Last updated at Posted at 2022-03-09

ユーザーの編集機能を実装する。

編集の時に登録したパスワードは変更しないようにしたいので、今回の編集項目にはパスワードは入れない。

パスワードを不要にするための手順は以下の通り。

ますはcontroller/users/registrations_controller.rbを編集する。

controller/users/registrations_controller.rb
 # 以下を追記する
  protected
   def update_resource(resource, params)
    resource.update_without_password(params)
  end

※registrations_controller.rbを生成するためには、ターミナルでrails g devise:controllers usersを実行する必要がある

続いてroutes.rbを編集。

routes.rb
Rails.application.routes.draw do

#以下を追記する
  devise_for :users, controllers:{
    registrations: 'users/registrations',
  }

次にバリデーションに追記する。

models/user.rb
 VALID_PASSWORD_REGEX = /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]+\z/i
  validates :password, length: { minimum: 6 }, format: { with: VALID_PASSWORD_REGEX }, on: :create
  #passwordのバリデーションの最後に on: :create を追記する

最後にcontrollers/users_controller.rbを編集。

controllers/users_controller.rb
  def edit
  end

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

  private
  def user_params
    params.require(:user).permit(:department_name, :image)
  end

これで完成!
のはずが、挙動を確認すると、編集後に詳細ページへ遷移させたはずが、ルートパスへ飛んでいる。
DBを確認するとデータの更新もされていない。

そもそもなぜルートパスへ遷移するかがわからない。更新に失敗したら、再び編集ページへ戻るように条件分岐しているはずなのに・・・

ビューファイルを見返してみると、1点気になる記述が。

views/users/edit.html.erb
<%= form_with model: current_user, url: user_registration_path, class: 'registration-main', local: true do |f| %>

urlが新規登録ページに設定されている。
もしかしてこれが原因では?
urlをまるまる削除し、以下に修正してみる。

views/users/edit.html.erb
<%= form_with model: current_user, class: 'registration-main', local: true do |f| %>

挙動確認すると、DBも更新され、詳細ページに遷移することもできた。

1
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
1
0