2014-12-06 84 views
0

我在添加將用戶關聯到多個帖子的新遷移後測試了一些關聯。Devise在User.first後返回nil

class DeviseCreateUsers < ActiveRecord::Migration 
    def change 
     create_table(:users) do |t| 
     ## Customization 
     t.string :name 
     ## Database authenticatable 
     t.string :email,    null: false, default: "" 
     t.string :encrypted_password, null: false, default: "" 

     ## Recoverable 
     t.string :reset_password_token 
     t.datetime :reset_password_sent_at 

     ## Rememberable 
     t.datetime :remember_created_at 

     ## Trackable 
     t.integer :sign_in_count, default: 0, null: false 
     t.datetime :current_sign_in_at 
     t.datetime :last_sign_in_at 
     t.string :current_sign_in_ip 
     t.string :last_sign_in_ip 

     ## Confirmable 
     t.string :confirmation_token 
     t.datetime :confirmed_at 
     t.datetime :confirmation_sent_at 
     t.string :unconfirmed_email # Only if using reconfirmable 

     ## Lockable 
     # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts 
     # t.string :unlock_token # Only if unlock strategy is :email or :both 
     # t.datetime :locked_at 


     t.timestamps 
    end 

    add_index :users, :email,    unique: true 
    add_index :users, :reset_password_token, unique: true 
    # add_index :users, :confirmation_token, unique: true 
    # add_index :users, :unlock_token,   unique: true 
    end 
end 

我遷移後,我應該用 u = User.first 測試獲得的代碼塊,確保一切運行順利。

User Load (0.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1 
=> #<User id: 1, name: nil, email: "[email protected]", encrypted_password: "$2a$10$702fd8Io3WH7UTWoTY3rUeUJBcFVlsq8/K6ypPKZUQni...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, confirmation_token: nil, confirmed_at: "2013-04-29 20:25:26", confirmation_sent_at: "2013-04-29 20:25:09", unconfirmed_email: nil, created_at: "2013-04-29 20:25:09", updated_at: "2013-04-29 20:25:26"> 

,但我得到了nil

2.1.5 :001 > u = User.first 
    User Load (0.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1 
    => nil 

這是一件壞事?爲什麼沒有任何東西出現?

+0

你測試之前,你需要確保你的數據庫中有數據。看起來像我,你的數據庫是空的... – Edward 2014-12-06 20:21:08

回答

3

您的數據庫目前爲空。因此你得到一個零。您可以這樣做:

1)在前端使用設計註冊功能向表中添加新用戶。

2)在這樣的分貝/ seeds.rb文件添加種子數據:從命令提示

User.find_or_create_by(:email => '[email protected]', :password => 'password', :password_confirmation => 'password') 

運行rake db:seed。種子數據是您想要添加到數據庫中以便應用程序按需運行的初始數據。

3)用Rails的控制檯:運行在命令提示符rails c和做到這一點:

User.create(:email => '[email protected]', :password => 'password', :password_confirmation => 'password') 
+0

好,非常感謝! – 2014-12-06 20:41:24

1

你需要做這樣的事情在控制檯添加的第一個用戶:

user = User.new(:email => '[email protected]', :password => 'testingpassword', 
:password_confirmation => 'testingpassword') 
user.save 

設計不會爲您創建一個默認的用戶,所以直到你創建一個,西港島線user.first回來作爲無