4

So to get a record in the User model I run

 @user = User.find(1)

Then to change an attribute:

 @user.active = false

It then returns false

When I run

 @user.save

I get

(0.2ms)  BEGIN
(0.3ms)  SELECT 1 FROM `users` WHERE (LOWER(`users`.`username`) = LOWER('sean') AND `users`.`id` != 1) LIMIT 1
(0.3ms)  SELECT 1 FROM `users` WHERE (LOWER(`users`.`email`) = LOWER('sean@gmail.com') AND `users`.`id` != 1) LIMIT 1
(0.6ms)  ROLLBACK
 => false 
1
  • 2
    Try @user.save then check @user.errors to see if there are any validation errors on save. Sep 7, 2011 at 2:56

2 Answers 2

17

Try this to see if errors are being thrown

@user.save!

If your @user.save is returning false then it means there's an error and something is preventing it from being saved. You can use @user.errors at that point to see what the errors are.

4
  • It was a password length validation error that was coming up. I changed it to include :on => :create, :update
    – chief
    Sep 7, 2011 at 4:14
  • Actually, It won't work if I have :on => :update. The console asks for a min length password. Any Advice?
    – chief
    Sep 7, 2011 at 4:33
  • 1
    It seems you added a validation to password AFTER your user already was in the database. You have two options 1) remove the password length validation or 2) update the user password so it meets validation. I'd go with #2. Just do @user.password = 'somevalidpassword' and then try saving.
    – Dty
    Sep 7, 2011 at 5:43
  • I deleted the database and made a new one and new user. But still the problem remains. If I have :on => :update for the password validation. It will want a password for any attribute update it seems.
    – chief
    Sep 7, 2011 at 6:44
3

Had the same issue. Doing this managed to solve it:

@user.save(validate: false)

Here is the link to original answer: How to skip validations as admin during update_attributes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.