3

我遵循 Michael Hartl 的 RoR 教程,我在第 9.3 章“显示所有用户”到目前为止一切都很好,但现在我在尝试从 SQlite 数据库检索我的用户时为 nil:NilClass 获得了一个未定义的方法“每个”。这是我的控制器

class UsersController < ApplicationController

before_filter :signed_in_user, only: [:index, :edit, :update]
before_filter :correct_user,   only: [:edit, :update]

.
.
.

def index
@users = User.all
end
end

    and my index.html.erb

<ul class="users">

<% @users.each do |user| %>
<li>
<%= gravatar_for user, size: 52 %>
<%= link_to user.name, user %>
</li>
<% end %>
</ul>

使用此代码,我得到 nil:NilClass 的错误未定义方法“每个”

当我将其更改为

<ul class="users">
<% if @users %>
<% @users.each do |user| %>
<li>
<%= gravatar_for user, size: 52 %>
<%= link_to user.name, user %>
</li>
<% end %>
<% end %>
</ul>

尽管我的数据库中有用户,但我可以渲染视图但显示 0 个用户。我手动创建了一些,还使用了“faker”gem 来生成一些。在 Rails 控制台中键入 User.all 会返回一个包含 100 个用户的数组。我似乎无法在这里找到缺失的链接。我还使用 SQlite 数据库浏览器应用程序来检查我的用户模型,其中我也有 100 个用户。我已经为此做了很多工作,但似乎无法弄清楚。

这也是我的 User.rb

class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password

before_save { |user| user.email = email.downcase }
before_save :create_remember_token

validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence:   true,
format:     { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true

private

def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
4

2 回答 2

3

奇怪的User.all是返回nil而不是空数组[]。尝试以下操作:

  1. 确保您已运行任何待处理的迁移

    rake db:migrate
    
  2. 如果上一步没有运行任何迁移,请尝试擦除数据库并重新开始,只是为了更好地衡量:

    rake db:drop
    rake db:create db:migrate db:seed
    
  3. 进入 Rails 控制台,并确保User.all行为正确

    rails c
    >> User.all
      User Load (0.4ms)  SELECT "users".* FROM "users" 
    => []
    >> exit
    
  4. If this all works, try putting some debug statements into your controller (using pry or the ruby debugger is optimal, but even some puts statements will suffice here) to examine the value of @users

  5. Next, you'll want to either add some seeds to the database (edit db/seeds.rb and run rake db:seed) or use scaffolded forms to add some users.

于 2012-07-30T08:11:44.377 回答
0

another really helpful debugging tool is the pry gem. you can find it on github.

it will stop program execution at the point in your code where you put the command:

binding.pry

and allow you to have a rails consol- access variables, call methods... whatever.

it's a great handy tool for debugging.

于 2012-07-31T02:30:59.243 回答