Home > Mobile >  NoMethodError in Articles#show ( undefined method `each' for nil:NilClass ) [closed]
NoMethodError in Articles#show ( undefined method `each' for nil:NilClass ) [closed]

Time:09-16

error

Am trying to render "latest articles" on my article blog sidebar and am getting the error above, the same code works fine for the article index page but shown errors in the show page.

latest articles partial

and my article controller below. articles_controller

CodePudding user response:

undefined method 'each' for nil:NilClass means that there is no method each that works with an object of class Nil. It works for the #index method because you are passing the variable @articles there. But in #show, you are passing a variable called @article. So you @articles variable in the show method does not exist therefore it has a default value nil. Your code in the index iterates over all articles, that is what each is doing. But in #show you want to show only one article so you should skip the each block, and use an article like @article.title

CodePudding user response:

should use to_a method, like this.

Article.all.to_a.each do l item l end

CodePudding user response:

Found the solution, the code below worked for me.

<% Article.all.order("created_at Desc").limit(5).each do | article | %>
<%= article.title %>
<% end %>

Note: I ordered and limit the article to 5 at the same time and it's in my VIEW.

  • Related