当我在 Rails 中更新用户模型时发生回滚?

Rollback happens when I update user model in Rails?

当我尝试更新用户简介时,rails 回滚。

这是我的控制器:

class UsersController < ApplicationController
skip_before_action :authorize, only: [:create]

def create
    user = User.create!(user_params)
    session[:user_id] = user.id
    render json: user, status: :created
end

def show
    render json: @current_user, include: :animes
end

def update
    user = User.find_by(id: params[:id])
    user.update(user_params)
    render json: user, status: :ok
end

private

def user_params
    params.require(:user).permit(:username, :password, :password_confirmation, :bio, :avatar, :email)
end

这是我的模型:

class User < ApplicationRecord
has_secure_password
has_many :anime_lists
has_many :animes, through: :anime_lists
has_many :manga_lists
has_many :mangas, through: :manga_lists

validates :username, presence: true, confirmation: 
{case_sensitive: false}, uniqueness: true, length: {in: 6..30}
end

这是控制台的图片:Rails console

我什至在前端用更新后的简历取回了响应对象,但实际上并没有更新。

为什么会这样?

我们需要检查您的型号。如果您在那里进行验证,它可以拒绝您的更新。一个好的做法是使用 flash 消息在视图中显示有关成功更新或错误的答案。

事务中的 SELECT 1 ... 查询看起来像是检查唯一性的查询。事实上,您的模型有一个 uniqueness validation。如果在此查询之后没有插入数据,则此验证很可能失败,因此 Rails 回滚在此 save 操作的概念中完成的所有事情。

这意味着您试图使用数据库中已存在的用户名创建用户。

为了准确了解什么时候出错并向用户提供反馈,我建议将验证错误返回给用户。这可以通过将您的控制器方法更改为:

def update
  user = User.find_by(id: params[:id])
  
  if user.update(user_params)
    render json: user, status: :ok
  else
    render json: user.errors, status: :unprocessable_entity
  end
end