【问题标题】:"NoMethodError in Users#show" Hartl Chapter 7“Users#show 中的 NoMethodError”Hartl 第 7 章
【发布时间】:2013-09-10 20:02:24
【问题描述】:

Users#show 中的 NoMethodError

错误:nil:NilClass 的未定义方法“名称”

我一直在关注 Hartl 的 Rails 4.0 教程,但我已经坚持了几天。该错误将第 1 行突出显示为“show.html.erb 文件”中的问题。此外,ruby 的 'private' 关键字不起作用,所以我在 'users_controller.rb' 中对其进行了散列,从而停止了错误。我会非常非常感谢任何帮助。谢谢。

app/views/show.html.erb

<% provide(:title, @user.name) %>
<div class="row">
  <aside class="span4">
    <section>
      <h1>
        <%= gravatar_for @user %>
        <%= @user.name %>
      </h1>
    </section>
  </aside>
</div>

users_controller.rb

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

  def new
    @user = User.new

        def create
    @user = User.new(user_params)
    if @user.save
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      render 'new'
    end
  end

  #private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end
end
end

【问题讨论】:

  • 你没有告诉我们错误是什么......
  • 上面更新有错误

标签: ruby ruby-on-rails-3 ruby-on-rails-4


【解决方案1】:

您的代码中有两个问题:

first:你有两个函数名为new,第一个应该是show

second:你在第二个函数的末尾错过了end(将它从控制器的末尾移开)

【讨论】:

  • 哦,是的。我已经从控制器的结尾移动了结尾。我认为这将使“私人”现在可以工作?
【解决方案2】:

您可能没有设置@user 实例变量。您的控制器中应该有:

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

【讨论】:

  • 它在上面的'users_controller.rb'中。等等,不,不是。我把它放在哪里?
  • @Abraham 无论在哪里。它应该只是UsersController 类的公共实例方法。
  • @Abraham 你应该用show 替换你的第一个new 定义。
  • 我在顶部添加了“def show”等,现在页面加载了。我很惊讶我错过了那个。一定是代码盲了。谢谢!
猜你喜欢
  • 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
相关资源
最近更新 更多