Ruby on Rails update_attibutes not working

294 views Asked by At

I am trying to set an user as admin, the method is:

def set_user_admin
    if admin_true? == true
      user = User.find(params[:format])
      if user == nil
        redirect_to managements_path
      else
        user.update_attributes(admin: true, assistant: true, 
          businessman: true)
        redirect_to managements_path
        flash[:notice] = "The user #{user.name} is an admin user now"
      end
    else
    end
  end

The method run just fine, but is not saving in data base. Some validation is stopping the action. Then I run the command in terminal:

u = User.find_by_id(3)
u.update_attributes(admin: true)
(0.1ms)  rollback transaction
=> false
u.errors
@messages={:password=>["Choose a password", "Your password must be at least 4 characters
"], :password_confirmation=>["You must confirm your password
"]}

So, I can't update user as admin because the password validations are called in the action.

Does anyone know why password and update_password validation is being called in update_attributes? I do not understand why

2

There are 2 answers

1
VAD On BEST ANSWER

update_attributes method is calling save method with parameter perform_validations = true on the object (user in your case). So any validations model User has will be performed after calling update_attributes method. It's the natural behavior.

For not to perform validations you may want to use update_attribute method. It calls save method with parameter perform_validations = false

update

update_attribute is deprecated in rails 4 so you may find useable update_column instead

0
Junan Chakma On

update_attributes method triggers model validations and callbacks. Try update_column method instead of update_attributes method.