undefined метод `each 'для nil: NilClass - требуется помощь - PullRequest
0 голосов
/ 23 января 2020

Я учу себя Ruby на Rails и пытаюсь создать блог с помощью учебника. Я видел некоторые из этих ответов, и кажется, что мой синтаксис правильный, но я получаю ошибку в заголовке.

Вот мой код article_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

И вот мой индекс. 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 %>

Буду признателен за любую помощь, которую смогу получить. Спасибо.

1 Ответ

0 голосов
/ 23 января 2020

Я думаю, что ваш синтаксис в методе index неправильный.

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

Должен быть

@articles = Article.all.paginate(page: params[:page], per_page: 5)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...