Home > OS >  Rollback happens when I update user model in Rails?
Rollback happens when I update user model in Rails?

Time:12-15

When i try to update the user bio, rails rollsback.

Here's my controller:

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

Here is my model:

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

And here is a picture of the console: Rails console

I even get back the response object on the front end with the updated bio, but its not actually updated.

Why is this happening?

CodePudding user response:

The SELECT 1 ... query inside the transaction looks like the query checking for uniqueness. And in fact, your model has a uniqueness validation. When there is no data inserted after this query then there is a high chance that this validation failed and therefore Rails rolls back all things done in the concept of this save operation.

That means you tried to create a user with a username that already exists in the database.

To see exactly what when wrong and to give the user feedback I suggest returning validation errors to the user. This could be done by changing your controller method to:

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

CodePudding user response:

We need to check your model. If you have validations on there, it can refuse your update. A good practice is to use flash message to show in the view the answer about successful updates or errors.

  • Related