nil:NilClass的未定义方法`each'-需要帮助

问题描述 投票:0回答:1

我正在自学Ruby on Rails,并尝试通过教程构建博客。我看到了其中一些答案,似乎我的语法正确,但是标题出现错误。

这是我的articles_controller代码:

class ArticlesController < ApplicationController
    before_action :set_article, only: [:edit, :update, :show, :destroy]

    def index
        @articles = Article.paginate(page: params[:page], per_page: 5)
    end

    def new
        @article = Article.new
    end

    def edit
    end

    def create
        @article = Article.new(article_params)
        @article.user = User.first
        if @article.save
            flash[:success] = "Article was successfully created"
            redirect_to article_path(@article)
        else
            render 'new'
        end
    end

    def update
        if @article.update(article_params)
            flash[:success] = "Article was updated"
            redirect_to article_path(@article)
        else
            flash[:danger] = "Article was not updated"
            render 'edit'
        end
    end

    def show

    end

    def destroy
        @article.destroy
        flash[:danger] = "Article was deleted"
        redirect_to articles_path
    end

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

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

这是我的index.html.erb:

<h1 align="center">Listing all articles</h1>
<% @articles.each do |article| %>
 <div class="row">
  <div class="col-xs-8 col-xs-offset-2">
   <div class="well well-lg">
    <div class="article-title">
     <%= link_to article.title, article_path(article) %>
    </div>
    <div class="article-body">
     <%= truncate(article.description, length: 100) %>
</div>
    <div class="article-meta-details">
     <small>Created by: <%= article.user.username if article.user %>, <%= time_ago_in_words(article.created_at) %> ago, last updated: <%= time_ago_in_words(article.updated_at) %> ago</small>
    </div>
    <div class="article-actions">
     <%= link_to "Edit", edit_article_path(article), class: "btn btn-xs btn-primary" %>
     <%= link_to "Delete", article_path(article), method: :delete, data: { confirm: "Are you sure you want to delete this article?"}, class: "btn btn-xs btn-danger" %>
    </div>
   </div>
  </div>
 </div>
<% end %>

我将不胜感激。谢谢。

ruby-on-rails ruby
1个回答
0
投票

我认为您在index方法中的语法是错误的。

@articles = Article.paginate(page: params[:page], per_page: 5)

应该是

@articles = Article.all.paginate(page: params[:page], per_page: 5)
© www.soinside.com 2019 - 2024. All rights reserved.