當我嘗試更新用戶 bio 時,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 控制臺
我什至用更新后的 bio 取回前端的回應物件,但實際上并沒有更新。
為什么會這樣?
uj5u.com熱心網友回復:
該SELECT 1 ...交易看起來像是唯一的查詢檢查內部查詢。事實上,您的模型具有唯一性驗證。如果在這個查詢之后沒有插入資料,那么這個驗證很可能失敗,因此 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
uj5u.com熱心網友回復:
我們需要檢查您的型號。如果您在那里有驗證,它可以拒絕您的更新。一個好的做法是使用 flash 訊息在視圖中顯示有關成功更新或錯誤的答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/380418.html
