2012-05-04 17 views
2

私はhttp://ruby.railstutorial.org/のチュートリアルをMichael Hartlによって行っています。このようになりますどの6.27をリストRuby on Rails 3チュートリアル

私は特にコードチャプター6によ

require 'spec_helper' 

    describe User do 

     before do 
     @user = User.new(name: "Example User", email: "[email protected]", 
         password: "foobar", password_confirmation: "foobar") 
     end 

     subject { @user } 

     it { should respond_to(:name) } 
     it { should respond_to(:email) } 
     it { should respond_to(:password_digest) } 
     it { should respond_to(:password) } 
     it { should respond_to(:password_confirmation) } 

     it { should be_valid } 
    end 

今すぐユーザーオブジェクトは、次のようになります

class User < ActiveRecord::Base 
     attr_accessible :email, :name, :password, :password_confirmation 
     before_save { |user| user.email = email.downcase } 

     validates :name, presence: true, length: {maximum: 50} 
     VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 
     validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniquenes 
     {case_sensitive: false} 
    end 

Userオブジェクトは、6つの属性があります:IDを、名前、電子メール、created_at、updated_at、password_digest。 password_digestは、ハッシュされたパスワードが保存される場所です。しかし、あなたが見ることができるように、passwordとpassword_confirmationはデータベースにありません。 password_digestのみです。著者は、それらをデータベースに格納する必要はなく、メモリ内に一時的に作成するだけであると主張しています。私はRSpecのテストからコードを実行するときしかし:

@user = User.new(name: "Example User", email: "[email protected]", 
        password: "foobar", password_confirmation: "foobar") 

私は私に言って、エラーがパスワードとpassword_confirmationは未定義のフィールドを取得します。これをどうやって回避するのですか?

マイク

答えて

5

attr_accessibleちょうど彼らが存在しない場合の特性は、それが実際にプロパティを作成しません、大量の割り当てに設定することが許可されているレールを伝えます。

あなたはこれらのプロパティは、データベース内のフィールドに対応していないためpasswordpassword_confirmationためattr_accessorを使用する必要があります。男は別の名前をattr_accessible与えるために何かをする必要があり

class User < ActiveRecord::Base 
    attr_accessor :password, :password_confirmation 
    attr_accessible :email, :name, :password, :password_confirmation 
    ... 
end 
+0

レール。 ..私は非常に多くの人がattr_accessorとattr_accessibleを混乱させるのを見ました。 – Abid

+0

私は問題を見つけました。 Userクラスの中にhas_secure_passwordという行がありませんでした。私はなぜ、どのようにこの作品がわからない。誰かが私を啓発してくれますか? – mikeglaz

+0

['has_secure_password'はこちら](https://github.com/rails/rails/blob/master/activemodel/lib/active_model/secure_password.rb)のソースとドキュメントを見ることができます。これは基本的な機能で、少し余分な機能をモデルに組み込んでいます( 'attr_reader:password'と、パスワードプロパティが変更されたときに自動的に暗号化されたパスワード/ password_digestを生成するセッター)。 – pjumble

関連する問題