nil的未定义方法'each':NilClass,用于@topics

问题描述 投票:-2回答:1

我想在页面上显示内容。我有:

index.html.erb

<if !user_signed_in? %>
  <%= link_to 'Download Topics', resumes_url, :class => 'btn btn-danger' %>
  <%= form_tag topics_path, :method => 'get' do %>
    <%= text_field_tag :search, params[:search] %>
    <%= submit_tag "Search" %>
  <% end %>

  <% @topics.each do |topic| %>
    <div class="topic">
      <h3><%= topic.title %></h3>
      <p><%= topic.id %></p>
      <p class="text-justify" ><%= topic.body %></p>
      <p><%= topic.date %></p>

      <%= image_tag topic.image.url, class: "topic-show" if topic.image? %>
    </div>

    <% if current_user && current_user.admin? %>
      <%= link_to "Edit", edit_topic_path(topic), :class => 'btn btn-default' %>
      <%= link_to "Destroy", topic, :class => 'btn btn-default', method: :delete, data: {confirm: 'Are you sure?'} %>
    <% end %>
    <%= link_to "Show", topic_path(topic), :class => 'btn btn-default' %>
  <% end %>
<div>
<%= will_paginate @topic, renderer: BootstrapPagination::Rails %>
</end>

topics_controller.rb,索引操作

class TopicsController < ApplicationController
  before_action :authenticate_user!, except: [:show, :index, :update, :destroy]

  def index
    @topics = Topic.search(params[:search]).paginate(:page => params[:page], :per_page => 5
    @topics = Topic.all
  end
end

我收到了一个错误

undefined method `'each'` for `nil:NilClass`

错误是在<% @topics.each do |topic| %>抛出的。

我不确定该怎么做。我试图添加:

@topics = Topic.all

topics#index,但似乎没有解决问题。

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

此错误仅表示@topics为空。

要解决此问题,您需要在观看控制台时刷新页面。

检查这些行运行时正在运行的查询:

@topics = Topic.search(params[:search]).paginate(:page => params[:page], :per_page => 5
@topics = Topic.all

如果您无法在控制台中发现问题,请将查询复制到数据库GUI中并运行查询,修改它直到获得预期结果并编辑查询。

我认为你的问题可能与被传递的参数有关。

您应该在查询之前添加此信息,以查看您正在接收的参数。

p 'my params'
p params[:search]
p params[:page]

PS。我建议让你的per_page成为一个变量,它使得在通过代码查看所有硬编码值时更容易,并且当它们不在代码块的中间时更改它们。

© www.soinside.com 2019 - 2024. All rights reserved.