1

无法批量分配受保护的属性:密码、密码确认


这两个字段都没有映射到数据库中,它们只是我想用来启用一些很好的验证的表单中的字段。

这是我的模型类:

class User < ActiveRecord::Base
  attr_accessible :email, :password_hash, :password_salt
  attr_accessor :password, :password_confirmation

  before_save :encrypt_password

  validates_confirmation_of :password
  validates :password, presence: true
  validates :email, presence: true

  def encrypt_password
    if password.present?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
    end
  end
end

我的印象是,通过在 attr_accessor 方法中放置password和,它们不会被批量分配,但在这里我遇到了这个小问题。password_confirmation

有什么建议么?

这是我的迁移字段,因此您可以查看我的数据库中实际存在哪些字段。

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :email
      t.string :password_hash
      t.string :password_salt

      t.timestamps
    end
  end
end

我在这里想念什么?

4

2 回答 2

2

attr_accessible specifies a white list of model attributes that can be set via mass-assignment. attr_accessor creating an instance variable (@name) and a corresponding access method to read it. Also creates a method called name= to set the attribute.

class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation
  attr_accessor :password

  before_save :encrypt_password

  validates_confirmation_of :password
  validates_presence_of :password, :on => :create
  validates :email, presence: true

  def encrypt_password
    if password.present?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
    end
  end
end
于 2013-01-08T15:16:13.307 回答
1

您需要 在attr_accessible中添加:password_confirmation:password

于 2013-01-08T15:09:08.180 回答