St3
St3

Reputation: 401

Couldn't find Article with 'id'=1 and undefined method `title' for nil:NilClass in Rails app

I've been following the JumpStartLab Blogger 2 Project and I'm stuck on what seems to be something simple. I'm at this point Just scroll up a page where it says

@article = Article.find(params[:id])

Basically I've followed everything to a tee (I think) and after refreshing the browser after clicking the link for one of the articles I get the following error:

ActiveRecord::RecordNotFound in ArticlesController#show

Couldn't find Article with 'id'=1

My Articles_controller.rb looks like this

class ArticlesController < ApplicationController

  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

end

My index.html.erb looks like this

<h1>All Articles</h1>

    <ul id="articles">
    <% @articles.each do |article| %>
        <li>
            <%= link_to article.title, article_path(article), class: 'article_title', id: "article_#{article.id}" %>
        </li>
    <% end %>

</ul>

<%= link_to "Create a New Article", new_article_path, class: "new_article" %>

And my show.html.erb looks like this.

<h1><%= @article.title %></h1>
<p><%= @article.body %></p>
<%= link_to "<< Back to Articles List", articles_path %>

Pretty stuck here and can't figure it out. Also I noticed another problem. At first I forgot the

@article = Article.find(params[:id])

and I was plagued with this error which I assume will come back after I figure out the first issue.

NoMethodError in Articles#show show.html.erb where line #1 raised:

undefined method `title' for nil:NilClass

I've looked up similar questions but they all seem to be deeper into the program than I am and were talking about private methods which I don't think I'm dealing with yet. I posted both problems because I'm not sure if they are related or not. Any advice would help me out as this is really slowing me down. Thanks.

Upvotes: 2

Views: 2443

Answers (2)

I got the same error in a udemy course, i had not added a plural form of articles while redirecting the path. I had typed

article_path(article)

instead of

articles_path(article)

I hope this helps someone.

Upvotes: 0

smathy
smathy

Reputation: 27971

Based on the code you're showing, that shouldn't be able to happen, if the link is present on your index page, then your show method should be able to find it.

Maybe your index page is out of date, or using some cache that is no longer valid. Try reloading the page, or restarting your server (and if you do this, be sure to run spring stop so you get a full restart), I would also run rake tmp:clear to clear the cache, just in case.

Upvotes: 1

Related Questions