我已經搜索了幾個小時,嘗試了所有可能的修復方法。我無法完成這項工作。錯誤是:Rails未定義的方法'each'for nil:NilClass ...但它被定義
*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 – SeattleDucati