Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 4 - update user object and bypass model validations

I'm following Micahel Hartl's Rails tutorial to build a sample app. I've tried to explore a bit and add some different things-- so in the Users table I've added an account_balance column.

The problem is that the User model has a bunch of validations built in:

validates :name, presence: true, length: { maximum: 50 }
validates :username, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence:   true,
                  format:     { with: VALID_EMAIL_REGEX },
                  uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }

I have another function that attempts to update just the account_balance by doing:

buyer   = User.find(t.buyer_id)
buyer.account_balance -= item_price 
buyer.save

This fails to save. When I ran it in the rails console, it returned the following, which means nothing to me:

irb(main):055:0> u = User.first
  User Load (0.5ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
=> # all the user info here
irb(main):056:0> u.account_balance = 10.00
=> 10.0
irb(main):057:0> u.save
   (0.2ms)  begin transaction
  User Exists (0.3ms)  SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('[email protected]') AND "users"."id" != 1) LIMIT 1
   (0.1ms)  rollback transaction
=> false

I am guessing that the uniqueness constraint on the email is being violated, but I don't know why this would happen on an update?

like image 348
user101289 Avatar asked Mar 20 '14 21:03

user101289


2 Answers

Found it. Just pass validate: false to the save method.

buyer.save(validate: false)

http://api.rubyonrails.org/classes/ActiveRecord/Validations.html

like image 105
CWitty Avatar answered Nov 15 '22 08:11

CWitty


buyer = User.find(t.buyer_id)
buyer.account_balance -= item_price 
buyer.save(validate: false) # this skips the validation
like image 44
Fellow Stranger Avatar answered Nov 15 '22 06:11

Fellow Stranger