LoginSignup
0
0

More than 1 year has passed since last update.

[解決]ユーザーの編集ができない→passwordのバリデーションに原因があった

Last updated at Posted at 2021-09-20

はじめに

本記事は、現在私が戦っているエラーのないエラーの備忘録です。

内容

ユーザーの編集ができなくなってしまった。
1週間前は、普通に編集ができました。
また、特にコードいじってないはずなのに。

Image from Gyazo

コード

コントローラー

users_controller.rb
class UsersController < ApplicationController
  before_action :authenticate_user!

  def show
    @user = User.find(params[:id])
    @foods = @user.foods.order("created_at DESC")
  end

  def followings
    user = User.find(params[:id])
    @users = user.followings
  end

  def followers
    user = User.find(params[:id])
    @users = user.followers
  end

  def edit
    @user = User.find(params[:id])
    return redirect_to user_path if current_user.id != @user.id
  end

  def update
    @user = User.find(params[:id])
    return redirect_to user_path if current_user.id != @user.id

    if @user.update(user_params)
      redirect_to user_path(current_user.id)
    else
      render :edit
    end
  end

  private

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

end
  def update
    @user = User.find(params[:id])
    return redirect_to user_path if current_user.id != @user.id

    if @user.update(user_params)
      redirect_to user_path(current_user.id)
    else
      render :edit
    end
  end

ここが↑悪いのか。
binding.pryで確認したら、
@user.update(user_params)がfalseだった。。

だから、editページに残るのか。

モデル↓

user.rb
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many :foods, dependent: :destroy
  has_many :likes, dependent: :destroy
  has_many :liked_foods, through: :likes, source: :food
  has_many :relationships, foreign_key: :following_id
  has_many :followings, through: :relationships, source: :follower
  has_many :reverse_of_relationships, class_name: 'Relationship', foreign_key: :follower_id
  has_many :followers, through: :reverse_of_relationships, source: :following
  has_one_attached :icon
  has_many :comments

  validates :nickname, presence: true
  validates :password, format: {with: /\A(?=.*?[a-z])(?=.*?[\d])[a-z\d]+\z/i}

  def already_liked?(food)
    self.likes.exists?(food_id: food)
  end

  def is_followed_by?(user)
    reverse_of_relationships.find_by(following_id: user.id).present?
  end


end

ビュー↓

<%= render "shared/header2" %>
<div class="edit-mypage-contents">
  <h2 class="edit-mypage-title">EDIT MY PAGE</h2>
  <div class="mypage-main">
    <%= form_with model: current_user, local: true do |f| %>

      <div class="edit-mypage-intro">
        <div class="edit-mypage-intro-left">
          <div class="edit-user-icon">
            <h2 class="edit-user-icon-title">現在のアイコン</h2>

            <label class="edit-click-upload">
              <%= f.file_field :icon, class:"edit-food-image-text", type:"file" %>アイコンを変更
            </label>
            <% if @user.icon.present? %>
              <%= image_tag @user.icon, class: "mypage-image" %>
            <% else %>
              <i class="fas fa-user-circle mypage-image"></i>
            <% end %>
          </div>
        </div>

        <div class="edit-mypage-intro-right">
          <div class="edit-mypage-contents-info">
            <h2 class="edit-mypage-nickname">
              <%= f.label :nickname, "ニックネーム" %>
              <%= f.text_field :nickname, class:"edit-mypage-nickname-text", placeholder:"(40文字以内)", maxlength:"40" %>
            </h2>
          </div>

          <div class="edit-mypage-contents-info">
            <h2 class="edit-mypage-email">
              <%= f.label :email, "メールアドレス" %>
              <%= f.text_field :email, class:"edit-mypage-email-text" %>
            </h2>
          </div>

          <div class="edit-mypage-contents-info">
            <h2 class="edit-mypage-introduction">
              <%= f.label :introduction, "紹介文" %>
              <%= f.text_area :introduction, class:"edit-mypage-introduction-text", placeholder:"(200文字以内)", maxlength:"200" %>
            </h2>
          </div>
        </div>
      </div>

      <div class="mypage-edit-btn-contents">
        <%= f.submit "変更" ,class:"mypage-edit-btn" %>
      </div>

    <% end %>
  </div>
</div>

<%= render "shared/main_menu" %>
<%= render "shared/footer" %>

仮説

①インストールしたgemの影響

②この間にほぼCSSした触っていないから、そことの影響

③テストした際に、変なコードをいじった?

追記

モデルに原因があったようです。
以下の部分。
仮説の①②はハズレ、③は当たりだけど、我ながら大雑把な仮説だな〜。
Githubみて何がダメだったのかを洗い出しました。

変更前

user.rb
  validates :nickname, presence: true
  validates :password, format: {with: /\A(?=.*?[a-z])(?=.*?[\d])[a-z\d]+\z/i}

変更後

user.rb
  validates :nickname, presence: true
  validates :password, format: {with: /\A(?=.*?[a-z])(?=.*?[\d])[a-z\d]+\z/i}, on: :create

updateする時、まずパスワードを入力する形 になるらしいです。

on:createをつけることで、パスワードは新規登録時にのみバリデーションをかけるようにしました。

以下参考サイトです。
rails usersテーブルの値をpasswordなしで更新する
状況によってsave時に実行するバリデーションを切り替える
DeviseのUserテーブルにUpdateアクションでカラムを更新しようとするとうまくいかない現象について

終わりに

謎すぎるエラーの出ないエラーなので、
記事にしました。
あまり備忘録記事はいいとは思いませんが、
今後の自分のために残しておきます。。

明日はこれを解決します!!
頑張ります!

(追記)
結果的に、自分の知識不足によるものだったため、
まだまだだと感じました。

にてもdeviseは奥が深いなあ。

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