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

标签 ruby-on-rails ruby

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

下面是我的controller和index.html.erb

Controller

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

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>

我收到带有错误消息的 NoMethodError in Articles#index

undefined method `each' for nil:NilClass"

怎么了?我从网站上复制并粘贴了代码以查看我做错了什么,但仍然无法修复它。

最佳答案

使用@articles 而不是@article

def index
  @articles = Article.all ## @articles and NOT @article
end

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

你遇到了错误

undefined method `each' for nil:NilClass

因为在 index 操作中,您已经实例化了实例变量 @article(NOTICE singular) 并且正在使用 @articles (NOTICE plural) 在您的 index View 中,即 index.html.erb。因此,在 View 中,@articles(复数)将是 nil,因为它从未设置过。因此,错误。

关于ruby-on-rails - 文章#index 中的 Ruby on Rails 教程 NoMethodError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23639075/

相关文章:

ruby-on-rails - 告诉 gem 使用 Gemfile.lock 中的现有库

Ruby Watir Webdriver - 如何识别并单击 div 标签中的元素?

ruby-on-rails - Rails 的所见即所得编辑器 gem?

ruby-on-rails - Rails - 在不同的 Controller /模型中创建和编辑

arrays - 如何在 Ruby 中展平子数组?

ruby-on-rails - 我正在尝试使用 Action 电缆在 rails 5 中的两个 friend 之间创建聊天,但是所有用户都可以查看该消息,无论是否是 friend

mysql - Rails - 按条件和限制排序?

ruby-on-rails - 使用铁路创建模型图

ruby-on-rails - 是否可以在 Rails 中获取原始参数字符串?

ruby-on-rails - form_for 验证不起作用