文章#index中的Ruby on Rails教程NoMethodError

use*_*633 6 ruby ruby-on-rails

所以我在http://guides.rubyonrails.org/getting_started.html上关注官方的ROR教程, 我被困在第5.8节,它教我如何列出所有文章

以下是我的控制器和index.html.erb

调节器

class ArticlesController < ApplicationController
  def new
  end


  def create
    @article = Article.new(article_params)

    @article.save
    redirect_to @article
  end

  def show
    @article = Article.find(params[:id])
  end

  def index
    @article = Article.all
  end


  private
  def article_params
    params.require(:article).permit(:title, :text)
  end


end
Run Code Online (Sandbox Code Playgroud)

index.html.erb

<h1>Listing articles</h1>

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

  <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
    </tr>
  <% end %>
</table>
Run Code Online (Sandbox Code Playgroud)

我收到NoMethodError in Articles#index了错误消息

undefined method `each' for nil:NilClass"
Run Code Online (Sandbox Code Playgroud)

怎么了?我从字面上复制并粘贴了网站上的代码,看看我做错了什么,但仍无法解决.

Kir*_*rat 16

使用@articles与否@article

def index
  @articles = Article.all ## @articles and NOT @article
end
Run Code Online (Sandbox Code Playgroud)

@articles (复数)在语义上是正确的,因为您将在视图中显示文章集合而不是单个文章.

你收到了错误

undefined method `each' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

因为在index操作中,您已实例化实例变量@article(NOTICE singular)并在视图中使用@articles(NOTICE复数),indexindex.html.erb.因此,在视图中@articles(复数)将nil是从未设置的.因此,错误.

  • 非常感谢明确的解释,它帮助我解决了我遇到的问题. (2认同)