【问题标题】:Undefined method/NoMethodError in Rails 3Rails 3 中的未定义方法/NoMethodError
【发布时间】: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。仍然显示错误!

标签: ruby-on-rails-3 methods


【解决方案1】:

这是不正确的:

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

应该是:

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

在您的代码中,对象 @user 不存在,这就是您收到错误的原因。在迭代中,@users 中的每个用户都被一个接一个地放入user 对象中。

您的代码中的另一个错误是您使用了&lt;% @user.name %&gt;。这不会输出任何东西。如果你想输出用户的名字,你必须使用&lt;%= user.name %&gt;(注意等号)。

【讨论】:

  • 谢谢米莎!您对 (1) 没有 @ 和 (2) 的两个建议都将 = 符号放入 ruby​​ embed 工作!!
【解决方案2】:

不应该是:

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

user,不是@user

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 2018-06-16
    相关资源
    最近更新 更多