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?
Found it. Just pass validate: false
to the save method.
buyer.save(validate: false)
http://api.rubyonrails.org/classes/ActiveRecord/Validations.html
buyer = User.find(t.buyer_id)
buyer.account_balance -= item_price
buyer.save(validate: false) # this skips the validation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With