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
update_attributes
method is callingsave
method with parameterperform_validations = true
on the object (user
in your case). So any validations model User has will be performed after callingupdate_attributes
method. It's the natural behavior.For not to perform validations you may want to use
update_attribute
method. It callssave
method with parameterperform_validations = false
update
update_attribute
is deprecated in rails 4 so you may find useableupdate_column
instead