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

时间:2019-03-14 22:23:57

标签: ruby-on-rails ruby

我正在尝试在页面上显示内容。我有:

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| %>处引发了错误。

Error Shown Here

我不确定该怎么办。我尝试添加:

@topics = Topic.all

topics#index,但这似乎无法解决问题。

1 个答案:

答案 0 :(得分: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设置为一个变量,这样在遍历代码时可以更轻松地查看所有硬编码值,并在不位于代码块中间的情况下对其进行更改。

相关问题