2011-05-31 96 views
2

當我訪問http://localhost:3000/users時,它給我NoMethodError in Users#index。該錯誤是如下:Rails 3中未定義的方法/ NoMethodError 3

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 

我的視圖應用/視圖/用戶/ index.html.erb:

<% @users.each do |user| %> 
    hello!! <% @user.name %> 
<% end %> 

我的控制器應用/controllers/users_controller.rb

​​

我的路線。 RB文件有:

resources :users 

我所有的測試都通過了(使用RSpec的),包括測試用例規格/控制器/ 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,它讓我看到的用戶完美。代碼在應用程序/視圖/用戶/ show.html.erb:

<p> 
    <b>Name:</b> 
    <%= @user.name %> 
</p> 

我已經做了耙分貝:測試:準備,我認爲錯誤鏈接到數據庫或遷移。任何想法?謝謝!

+0

如果你向我們展示了你所得到的NoMethodError,它會幫助我們。 – 2011-05-31 03:35:56

+0

@Ryan:謝謝!剛剛在我的問題開始時添加了錯誤!我做了rake db:reset,然後rake db:migrate,rake db:test:prepare。它仍然顯示錯誤! – Sayanee 2011-05-31 06:53:17

回答

1

這是不正確的:

<% @users.each do |user| %> 
    hello!! <% @user.name %> 
<% end %> 

它應該是:

<% @users.each do |user| %> 
    hello!! <%= user.name %> 
<% end %> 

在你的代碼的對象@user不存在,這就是爲什麼你的錯誤。在迭代中,@users中的每個用戶都會逐個放入user對象中。

代碼中的另一個錯誤是您使用的是<% @user.name %>。這不會輸出任何內容。如果你想輸出用戶的名字,你必須使用<%= user.name %>(注意等號)。

+0

謝謝mischa!你對(1)no @和(2)的建議都是把ruby嵌入的=標誌工作了! – Sayanee 2011-05-31 07:53:29

+0

沒問題。不用謝。 – Mischa 2011-05-31 07:54:48

1

它不應該是:

<% @users.each do |user| %> 
    hello!! <% user.name %> 
<% end %> 

user,不@user

+0

謝謝!這工作:) – Sayanee 2011-05-31 07:52:46

相關問題