Rails nil:NilClass 的未定义方法“each”...但已定义

Rails undefined method `each' for nil:NilClass...but it is defined

我搜索了几个小时,尝试了所有可能的修复方法。我无法完成这项工作。错误是:

  *NoMethodError in Articles#index
  Showing /Users/myname/blog/app/views/articles/showall.html.erb where     line #21 raised:
undefined method `each' for nil:NilClass*

showall.html.erb是一个观点。它是从 'article' 控制器渲染的。 (都在下面发布)。有一条通往 showall 的路线,而且效果很好。目前路由配置为:

get 'article/showall'

但是,我也试过:

resources :articles do
  get 'showall'
resources :comments

两条路线都有效,但都没有对问题产生影响。

控制器中有一个方法,它不是私有的:

def showall
   @articles = Article.all
end

视图中有问题的代码是:

 <% @articles.each do |article| %>
 <tr>
  <td><%= article.title.truncate(30) %></td>
  <td><%= article.author %></td>
  <td><%= article.manufacturer %></td>
  <td><%= article.model %></td>
  <td><%= article.displacement %></td>`

<% end %>

我实际上是从 index.html.erb 视图中剪切并粘贴了一段代码,它工作得很好。我已经尝试了我能想到的多元化的每一个细微差别。任何帮助将不胜感激。

本控制器适用部位:

class ArticlesController < ApplicationController
 skip_before_action :authorize, only: [:index, :show, :showall]

 #Filter used to catch nonlogged in users 
 before_filter :require_user, :only => [:index]

#method that checks if logged in, sends them to showall if not.
def require_user
unless User.find_by(id: session[:user_id])
  render 'showall', :notice => "Please log in to read articles."
end
end

def index

@articles = current_user.articles

end

#should list articles, but throws undefined method 'each' error
def showall
@articles = Article.all
end

全貌如下:

 <%= render "menu" %>

 <body>
 <font color="yellow"><%= flash[:notice] %></font>
 <br>
 <font color="grey">Motorcycle Articles</font>
 <%= link_to 'Post New Article', new_article_path %> 
 <br>

 <table>
 <tr>
 <th>Title</th>

 <th>Author</th>
 <th>Brand</th>
 <th>Model</th>
 <th>Displacment</th>
 <th>Last Edited On:</th>
 <th>Article</th>
 </tr>
 <% @articles.each do |article| %>
  <tr>
  <td><%= article.title.truncate(30) %></td>
  <td><%= article.author %></td>
  <td><%= article.manufacturer %></td>
  <td><%= article.model %></td>
  <td><%= article.displacement %></td>

  <% end %>
  </table>
  <br>
   All articles are property of their respective owners.

 </body>

您正在调用呈现视图的渲染 'showall'。这与调用控制器操作的 'redirect_to' 不同。由于您将 @articles 的值设置为 nil 值(current_user 未设置),因此您会收到此错误。

为了澄清,您需要在呈现视图之前 redirect_to 'showall' 操作或重新定义 @articles 以等于 Article.all。我个人会重定向。

路由正在触发索引操作,请参阅:

NoMethodError in Articles#index

您收到错误消息是因为 current_user.articles 为零。

您需要确保 Articles#showall 出现在日志中,这意味着调用了 showall 方法。

创建路线:

get '/articles', to: 'Articles#showall'
resources :articles

不推荐这样做。有几个部分需要改进。但它应该会使错误消失。

修改您的 routes 文件

routes.rb

resources :articles do
  collection do
    get 'showall'
  end
end