不确定为什么会发生这种情况:
2.0.0p247 :001 > User.column_names
=> ["id", "user_name", "email", "password_digest", "created_at", "updated_at", "register_key", "culminated", "remember_token", "register_token_created_at", "profile_image", "licence_image", "first_name", "last_name", "nearest_town"]
2.0.0p247 :002 > user1 = User.create(user_name: 'james', email: 'james@killbots.com', first_name:'jj', last_name:'jj', nearest_town:'mordor')
=> #<User id: nil, user_name: "james", email: "james@killbots.com", password_digest: nil, created_at: nil, updated_at: nil, register_key: nil, culminated: nil, remember_token: nil, register_token_created_at: nil, profile_image: nil, licence_image: nil, first_name: "jj", last_name: "jj", nearest_town: "mordor">
2.0.0p247 :003 > user1.update(user_name: 'killo')
=> false
而不是解决方案,您将如何从控制台调试此问题?
答案 0 :(得分:3)
您的User
记录未保存,可能是因为验证失败。
您应该通过以下方式检查其有效性:
user1.valid?
并显示错误:
user1.errors.full_messages
答案 1 :(得分:2)
如果你注意到:
2.0.0p247 :002 > user1 = User.create(user_name: 'james', email: 'james@killbots.com', first_name:'jj', last_name:'jj', nearest_town:'mordor')
=> #<User id: nil, user_name: "james", email: "james@killbots.com", password_digest: nil, created_at: nil, updated_at: nil, register_key: nil, culminated: nil, remember_token: nil, register_token_created_at: nil, profile_image: nil, licence_image: nil, first_name: "jj", last_name: "jj", nearest_town: "mordor">
根本没有创建用户记录(user1)。用户ID为零。您必须进行一些失败的验证。如果已在数据库中成功创建记录,那么您的用户id
永远不会是nil
主键。
尝试使用 User.create!,这样您就知道为什么没有创建记录,您将获得引发的确切异常。例如:
2.0.0p247:002&gt; user1 = User.create!(user_name:&#39; james&#39;,email:&#39; james@killbots.com' ;, first_name:&#39; jj&#39; ,last_name:&#39; jj&#39;, nearest_town:&#39;魔&#39)
答案 2 :(得分:0)
好像你的对象无效。正如Kirti所指出的那样,由于没有返回主键id,因此它没有被持久存储到数据库中。检查对象的有效性可以为您提供有关对象内容的更多信息。结帐导轨指南可分析validation。