【问题标题】:NameError in UsersController#show用户控制器中的名称错误#show
【发布时间】:2013-03-17 17:42:38
【问题描述】:

我目前正在编写 Michael Hartl 编写的 Ruby on Rails 教程。我试图通过在视图目录中创建一个带有嵌入式 ruby​​ 页面的 HTML 来为我的数据库中的每个用户添加一个页面。 show.html.erb 的代码如下:

    <%= @user.name %>, <%= @user.email %>

当我将用户添加到 user_controller.rb 文件时,它看起来像这样:

class UsersController < ApplicationController
    def show
       @user = User.find(params[:id])
    end

    def new
    end
  end

当我运行 rails 服务器并单击打开 users/1 URL 时,我收到 NameError 抱怨未初始化的常量。错误和跟踪如下:

NameError in UsersController#show
uninitialized constant UsersController::User

Rails.root: /usr/sample_app
Application Trace | Framework Trace | Full Trace

app/controllers/users_controller.rb:3:in `show'
actionpack (3.2.12) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.2.12) lib/abstract_controller/base.rb:167:in `process_action'
actionpack (3.2.12) lib/action_controller/metal/rendering.rb:10:in `process_action'
actionpack (3.2.12) lib/abstract_controller/callbacks.rb:18:in `block in process_action'
activesupport (3.2.12) lib/active_support/callbacks.rb:414:in         
.
.
.
.

请让我知道如何解决此问题,因为我无法通过我的规范测试并出现此错误。如果有人有任何建议或见解,我将不胜感激。谢谢。

【问题讨论】:

  • 好吧,你在app/models/user.rb 中定义了class User 吗?
  • 不,我没有。实际上,我在模型目录中找不到我的 user.rb 文件。这很奇怪,因为我知道我以前有过一个

标签: ruby-on-rails nameerror uninitialized-constant


【解决方案1】:

控制器文件名应为users_controller.rb

正如你在评论 you don't have any User model defined 中提到的。创建模型运行rails g model user name:string email:string。这将创建具有name and email 属性的User 模型。

试用 Rails scaffolding 并查看它创建了哪些文件(在 controller, model and views 中暂时忽略其他文件)并查看这些文件的内容。使用脚手架创建User如下:

     rails g scaffold user name:string email:string
     rake db:migrate 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多