2016-12-25 345 views
0

我按照[railstutorial] [rails tutorial]嘗試設置一個簡單的網站。 在此頁面中,在向Users表插入多條記錄後,我使用rails console,嘗試查找一些記錄。但所有發現都失敗了。「RecordNotFound:找不到用戶」in rails教程

任何人都可以解釋爲什麼它會失敗嗎?非常感謝

2.0.0-p247 :064 > User.all 
    User Load (0.3ms) SELECT "users".* FROM "users" 
=> #<ActiveRecord::Relation [#<User id: 1, name: "Shijie", email: "[email protected]", created_at: "2016-12-24 22:36:56", updated_at: "2016-12-24 22:36:56">, #<User id: 2, name: "chen jie", email: "[email protected]", created_at: "2016-12-24 22:37:36", updated_at: "2016-12-24 22:37:36">, #<User id: 3, name: "Michael Hartl", email: "[email protected]", created_at: "2016-12-25 20:56:58", updated_at: "2016-12-25 21:21:38">]> 
2.0.0-p247 :065 > User.find(name: "Shijie") 
    User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", nil]] 
ActiveRecord::RecordNotFound: Couldn't find User with 'id'={:name=>"Shijie"} 
    from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.2.0/lib/active_record/core.rb:154:in `find' 
    from (irb):65 
    from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.2.0/lib/rails/commands/console.rb:110:in `start' 
    from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.2.0/lib/rails/commands/console.rb:9:in `start' 
    from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:68:in `console' 
    from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:in `run_command!' 
    from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.2.0/lib/rails/commands.rb:17:in `<top (required)>' 

2.0.0-p247 :066 > User.find(email: "[email protected]") 
    User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", nil]] 
ActiveRecord::RecordNotFound: Couldn't find User with 'id'={:email=>"[email protected]"} 
    from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.2.0/lib/active_record/core.rb:154:in `find' 
    from (irb):66 
    from /home/shijiex/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.2.0/lib/rails/commands/console.rb:110:in `start' 

生成user.rb。

class User < ActiveRecord::Base 
    has_many :microposts 

end 

我的版本中的rails是Rails 4.2.0,雖然本教程中的rails是用於v5 +的。

回答

3

find方法將使用id列查找記錄。所以,就你的情況而言,它會檢查id的值email: "[email protected]",這顯然不存在。

如果你想比其他id一欄找到記錄,使用find_by方法並傳遞column namevalue作爲哈希。

User.find_by(email: "[email protected]") 

欲瞭解更多,請閱讀的find_by

+0

Oh..I文檔實在太careless..As頁中的示例使用'find_by'。謝謝 –

相關問題