rails 4 - 更新用户对象并绕过模型验证

时间:2014-03-20 21:38:30

标签: ruby-on-rails ruby activerecord

我正在关注Micahel Hartl的Rails教程来构建一个示例应用程序。我试图探索一下并添加一些不同的东西 - 所以在Users表中我添加了account_balance列。

问题在于User模型内置了一堆验证:

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 }

我有另一个功能,尝试通过执行以下操作来更新account_balance

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

无法保存。当我在rails控制台中运行它时,它返回了以下内容,这对我来说没有任何意义:

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('test@example.com') AND "users"."id" != 1) LIMIT 1
   (0.1ms)  rollback transaction
=> false

我猜测电子邮件的唯一性限制正在被违反,但我不知道为什么会在更新时发生这种情况?

2 个答案:

答案 0 :(得分:18)

找到它。只需将validate: false传递给保存方法。

buyer.save(validate: false)

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

答案 1 :(得分:2)

buyer = User.find(t.buyer_id)
buyer.account_balance -= item_price 
buyer.save(validate: false) # this skips the validation