Welcome#index 中的 NoMethodError - Rails 入门

NoMethodError in Welcome#index - Getting Started with Rails

Screenshot Photo

需要有关此错误的帮助。我无法弄清楚代码有什么问题。我在网上研究了相关主题,但找不到任何解决方案。下面是代码。

<!-- index.html.erb -->

<h1>Hello, Rails!</h1>
<%= link_to 'My Blog', controller: 'articles' %>
<%= link_to 'New article', new_article_path %>

<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
  </tr>

  <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
      <td><%= link_to 'Show', article_path(article) %></td>
      <td><%= link_to 'Edit', edit_article_path(article) %></td>
      <td><%= link_to 'Destroy', article_path(article),
              method: :delete,
              data: { confirm: 'Are you sure?' } %></td>
    </tr>
  <% end %>
</table>

这是来自控制器的代码。

# welcome_controller.rb
class WelcomeController < ApplicationController
  def index
  end
end

配置代码

# routes.rb
Rails.application.routes.draw do
  get 'welcome/index'
  resources :articles
  root 'welcome#index'
end

如有任何帮助,我们将不胜感激!

Undefined method each for nil:NilClass

错误是由于 @articlesnil。您应该在 welcome#index

中定义它
class WelcomeController < ApplicationController 
  def index
    @articles = Article.all
  end 
end

但是您可以调整 index.html.erb 以避免此类错误

<% unless @articles.blank? %>
  <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
      <td><%= link_to 'Show', article_path(article) %></td>
      <td><%= link_to 'Edit', edit_article_path(article) %></td>
      <td><%= link_to 'Destroy', article_path(article), method: :delete, data: { confirm: 'Are you sure?' } %></td>
    </tr>
  <% end %>
<% end %>

@Pavan 的回答是正确的,可以解决你的问题!当你开始的时候,我决定写这个答案来解释更多发生的事情:

您将 root 路由到 'welcome#index',即,当您点击 http://localhost:300/ 它时,您从 WelcomeController 调用了方法 index。我们习惯从 WelcomeController 中调用它的索引操作。

在 运行 此方法之后,它将(默认情况下)呈现文件 app/views/welcome/index.html.erb。看到图案了吗?动作名称与文件名相同,控制器名称与包含此文件的文件夹名称相同。

在此文件中,您使用的是 @articles。这是在 WelcomeController#index.

中定义的变量

您的问题:这个变量没有在控制器中定义,导致一个 nil 对象。即,它不存在。

解决方案:按照@Pavan 的建议定义此变量。

但是您可能会再次陷入同样的​​异常:如果您还没有保存文章。为了防止这种情况,您只需要检查@articles 是否为 nil,正如@Pavan 所建议的那样。

希望这个回答能澄清问题和解决问题的建议!