【发布时间】:2022-01-17 10:11:39
【问题描述】:
当我尝试更新用户简历时,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
我什至用更新的 bio 取回了前端的响应对象,但实际上并没有更新。
为什么会这样?
【问题讨论】:
-
我们需要检查您的型号。如果您在那里有验证,它可以拒绝您的更新。一个好的做法是使用 Flash 消息在视图中显示有关成功更新或错误的答案。
-
@PauloFelipeSouza 为我的模型添加了代码。是不是我的用户名对于长度要求来说太短了,因此它正在回滚?另外我没有使用视图,我的 rails 后端是一个 API。更新:我尝试使用不同的帐户,它可以工作,所以你是对的,它一定是一个验证问题。
-
检查是否更新... if user.update(user_params) render json: user, status: :ok else render json: user.errors.full_messages, status: :400 end
标签: ruby-on-rails ruby model-view-controller