Aleksander Jess
Aleksander Jess

Reputation: 171

Getting an "ActiveRecord::RecordNotFound in PostsController#show " out of nowhere

Okay, so I am trying to display index.html, and RoR is showing me something is up with... def show in posts_controller... Okay?

So the index.html.erb

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <% @posts.each do |post| %>
    <div class="post_wrapper">
        <h2 class="title"><%= link_to post.title, post%></h2>
        <p class="date"><%= time_ago_in_words(post.created_at)%></p>
    </div>
    <% end %>
</body>
</html>

posts_controller.rb

class PostsController < ApplicationController
    def index
        @posts = Post.all.order('created_at DESC')
    end

    def new
    end

    def create
        @post = Post.new(post_params)
        @post.save

        redirect_to @post
    end
    def show
        @post = Post.find(params[:id])
    end
    private

        def post_params
            params.require(:post).permit(:title, :body)
        end    
end

My guess was that it's because there was no attribute such as ID, so I changed params[:id] to params[:title] and still got the same error.

Can you please explain what's wrong and what needs to be fixed?

Upvotes: 0

Views: 165

Answers (3)

Aleksander Jess
Aleksander Jess

Reputation: 171

Okay, so I forgot about a basic thing.

After adding get 'posts/index in routes.rb everything works.

Upvotes: 0

Corey Gibson
Corey Gibson

Reputation: 343

Just starting out and even now I have found that in development the gem BetterErrors https://github.com/BetterErrors/better_errors gives you a great way to debug errors live, maybe you can install this gem and give it a try it will give you better error pages and the ability to see different vars live.

also, it looks like there the problem should be in your

<%= link_to post.title, post %>

it definitely needs to look something like this

<%= link_to(post.title, post_path(post)) %> 

or

<%= link_to post.tilte, post_path(post) %>

if this does not work you need to look at your routes and see if you have the route for the show page defined.

Upvotes: 0

Sridhar
Sridhar

Reputation: 149

Can you post the error that you are getting.

Just a wild guess, the issue could be in this line

<%= link_to post.title, post%>

If so, change it to

<%= link_to post.title, post_path(post) %>

Upvotes: 1

Related Questions