为什么 Ruby on Rails 一直告诉我一个未实例化的变量?

Why does Ruby on Rails keep telling me about an uninstantiated variable?

编辑:已解决,在 Brian Kunzig 的回答+评论中查看解决方案。

我决定在 Rails 上尝试 Ruby 并且一直 运行 解决这个问题。我一直在四处寻找这样的问题,但 none 的解决方案已经帮我解决了问题。似乎我经常写出一部分不正确的代码。所以这里有一些代码片段:

(忽略代码的用途,只是尝试一下)

我的控制器:

class AuthsController < ApplicationController

        def index
          @auths=Auth.all  
        end

        def new
          @auth=Auth.new
        end

        def show
          @auth=Auth.find(params[:id])
        end
end

我的index.html.erb:

<div style="margin: 0 auto; width:50%; text-align: center">
    <h1>Please authorise your use of this webpage and its database(s).</h1>
    <%= form_for :auth, url: auths_path do |f| %>

    <% if @auth.errors.any? %> ==> RAILS REPORTS ERROR IN CODE HERE
    <div id="error_explanation">
      <h2>
        <%= pluralize(@auth.errors.count, "error") %> prohibited
        this authentification from being saved:
      </h2>
      <ul>
        <% @auth.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <p>
    <%= f.label :username %><br>
    <%= f.text_field :username %>
  </p>

  <p>
    <%= f.label :password %><br>
    <%= f.text_field :password %>
  </p>

  <p>
    <%= f.submit %>
  </p>

<% end %>

</div>

所以,底线。例如,Rails 是说我不能在 form_for 块中使用 @auth。或者其他任何地方。它总是说它属于 NilClass 或类似的东西。它显然希望我以某种方式实例化它,但这还不足以使方法成为新方法并放入行中:@auth=Auth.new ?

我只是对这种情况感到困惑,因为我无法弄清楚它应该如何进行。非常感谢!

P.S。我正在使用 <%= form_for :auth, url: auths_path do |f| %> 因为它不接受 @auth,这就是下一行中的错误所在。我已经看到在控制器外部实例化它的解决方案 "on the go",但我想按照它应该完成的方式进行。

您应该将此表格放入 new.html.erb 文件而不是 indexindex 用于列出条目,而 newcreate 操作处理 POST 请求。您收到错误消息是因为您在创建 none 时试图列出所有 Auth。此外,如果您使用标准 rails 路由,您将通过 GET 请求发送表单。使用足智多谋的路由并将此表单放入该控制器的 new 视图中,它应该可以工作。

路由文件应该是:

resources :auths

这将自动提供所有必要的路由。如果您在修改后键入 rake routes,您将看到新生成的 url 和它们的帮助程序。您会注意到它为 createupdate 操作提供 POST/PUT 请求,而其他操作是 GET.