我的用户模型非常接近Michael Hartl的一个
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
validates :name, presence: true, length: { minimum: 3, maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[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 }
validates :about, length: { maximum: 300 }
...
end
尝试用户的update_attributes
时,我只能提供密码及其password_confirmation。
虽然我知道这是用户创建的预期行为,但是有一些用户属性未经其同意而设置,因此他的密码。
一个人应该如何实现这一目标?我寻找像has_secure_password, on: :create
这样的东西,但它不起作用。
奇怪的是,我可以一次保存一个属性,而不是使用update_attribute
(这仍然很安静,我希望我们可以做得更好)!
我忘了提到我在更新时尝试删除has_secure_password
并且效果很好,所以这绝对是罪魁祸首。有没有我错过的选项?我应该查看它的源代码吗?
irb(main):002:0> User.find(1).update_attribute(:confirmed_email, true)
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.2ms) begin transaction
(0.1ms) commit transaction
irb(main):003:0> User.find(1).update_attributes(:confirmed_email => true)
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.2ms) begin transaction
User Exists (0.5ms) SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('example@railstutorial.org') AND "users"."id" != 1) LIMIT 1
(0.1ms) rollback transaction
=> false
irb(main):004:0> User.find(1).update_attributes(:confirmed_email => true, password: 'NewPassword', password_confirmation: 'NewPassword')
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.2ms) begin transaction
User Exists (0.3ms) SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('example@railstutorial.org') AND "users"."id" != 1) LIMIT 1
Binary data inserted for `string` type on column `password_digest`
SQL (0.7ms) UPDATE "users" SET "password_digest" = ?, "updated_at" = ? WHERE "users"."id" = 1 [["password_digest", "$2a$10$CMxLD91SCHWcdhJ3ciU2jez4Zw.gD7o3JszBuOf0gY04MVap56dGy"], ["updated_at", Mon, 27 Jan 2014 21:38:36 UTC +00:00]]
(172.4ms) commit transaction
=> true