【发布时间】:2011-05-31 15:02:30
【问题描述】:
当我访问http://localhost:3000/users 时,它给了我NoMethodError in Users#index。错误如下:
NoMethodError in Users#index
Showing /Applications/XAMPP/xamppfiles/htdocs/rails_projects/TUTORIALS/todo/app/views/users/index.html.erb where line #2 raised:
undefined method `name' for nil:NilClass
Extracted source (around line #2):
1: <% @users.each do |user| %>
2: hello!! <% @user.name %>
3: <% end %>
Rails.root: /Applications/XAMPP/xamppfiles/htdocs/rails_projects/TUTORIALS/todo
Application Trace | Framework Trace | Full Trace
app/views/users/index.html.erb:2:in `block in _app_views_users_index_html_erb___3451413751309771876_2169723860_4451603425222664605'
app/views/users/index.html.erb:1:in `each'
app/views/users/index.html.erb:1:in `_app_views_users_index_html_erb___3451413751309771876_2169723860_4451603425222664605'
我的模型 user.rb:
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime
# updated_at :datetime
#
class User < ActiveRecord::Base
attr_accessible :name, :email
我的视图app/views/users/index.html.erb:
<% @users.each do |user| %>
hello!! <% @user.name %>
<% end %>
我的控制器 app/controllers/users_controller.rb
class UsersController < ApplicationController
def index
@users = User.all
end
我的 routes.rb 文件有:
resources :users
我所有的测试都通过了(使用 rspec),包括 spec/controllers/users_controller_spec.rb 中的测试用例:
describe "GET 'index'" do
it "should be successful" do
get 'index'
response.should be_success
end
end
当我访问http://localhost:3000/users/1 时,它完美地向我展示了用户。 app/views/users/show.html.erb 中的代码:
<p>
<b>Name:</b>
<%= @user.name %>
</p>
我已经完成了 rake db:test:prepare 并且我认为错误与 db 或迁移有关。任何想法?谢谢!
【问题讨论】:
-
如果你向我们展示你得到的 NoMethodError 将会对我们有所帮助。
-
@Ryan:谢谢!刚刚在我的问题开始时添加了错误!我做了 rake db:reset 然后 rake db:migrate, rake db:test:prepare。仍然显示错误!