【发布时间】:2015-06-14 05:07:37
【问题描述】:
我已经搜索了几个小时,尝试了所有可能的修复方法。我无法完成这项工作。错误是:
*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 是一个视图。它是从“文章”控制器呈现的。 (都在下面发布)。有一条可以展示的路线,而且效果很好。目前路由配置为:
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>
【问题讨论】:
-
您确定有一些文章保存在数据库中吗?
-
是的,我可以用 index.html.erb 列出它们
标签: ruby-on-rails each