Question

Can't mass-assign protected attributes: password, password_confirmation


Both of those fields are not mapped in the database, they are just fields in the form that I want to use to enable some nice validations.

Here is my model class:

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

I was under the impression that by placing password and password_confirmation in the attr_accessor method they would not be mass assigned, yet here I am with this little issue.

Any suggestions?

Here's my migration field so you can see what fields are actually in my database.

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

What am I missing here?

Was it helpful?

Solution

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

OTHER TIPS

You need to add :password_confirmation and :password in attr_accessible

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top