我下面這個視頻教程,學習如何從頭開始建立認證:未定義的方法'密碼」 <用戶:1123123123>
http://www.youtube.com/watch?v=O5RDisWr_7Q
這裏是我的用戶遷移文件:
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
而且我的控制器:
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(params[:users])
if @user.save
redirect_to root_url, :notice => "Signed up!"
else
render "new"
end
end
end
最後我的模型:
class User < ActiveRecord::Base
attr_accessible :email, :password_hash, :password_salt
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
現在,我想我知道爲什麼這個錯誤是射擊;顯然@user.save
調用試圖將password
中的值保存到用戶表中的密碼字段,但該字段在數據庫中不存在。在他提到,要修復這個bug視頻我應該補充:attr_accessible :password
到我的模型,它應該工作,但我得到了以下錯誤:
NoMethodError in UsersController#create
undefined method `password' for #
app/controllers/users_controller.rb:8:in `create'
有什麼建議?我只想利用使用強類型模型而不是寬鬆html字段的驗證。
做我這樣的傻瓜要通過大規模分配集合 - 認真寫出我的問題後,我發現我需要使用'attr_accessor:password'。 D'哦!我將閱讀訪問者和可訪問之間的區別。 – sergserg