我正在尝试在页面上显示内容。我有:
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
,但这似乎并不能解决问题。
发布于 2019-03-15 07:00:44
这个错误只是意味着@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设置为变量,这样可以更容易地在代码中查看所有硬编码的值,并在它们不在代码块中间时对它们进行更改。
https://stackoverflow.com/questions/55172919
复制相似问题