Mandeep Gill
Mandeep Gill

Reputation: 390

How to fix rails Couldn't find Post without an ID Error

I am new to rails and little know of ruby, I have just stared tutorial from Rails Guide 4.0. Everything was going fine just stuck on one Error : Couldn't find Post without an ID.

I did everything as in Rails Guide Getting Started Of Rails.

Here is code from rails guide :

def show
  @posts = Post.find(params[:id])
end

and Here is View Code :

<p>
  <strong>Title:</strong>
  <%= @posts.title %>
</p>

<p>
  <strong>Text:</strong>
  <%= @posts.text %>
</p>

After this code rails guide tell you should finally be able to create new posts. Visit localhost:3000/posts/new and give it a try!. But after create new post it showing me error.

I thought it could be issue because i didn't created index action yet so i done with index, After index action when i try to visit this address normally it should display all record from database but rather then display record showing same error : Couldn't find Post without an ID

I tried too many posts on stackoverflow but all related to some other actions that are not useful for me.

Please help me to fix this issue, i am just thinking it shouldn't be because i am following rails guide.

I am following rails getting started guide as it said i added index action and show action. So as in book it said with index action when you visit this address /posts you should see all posts and when you create new post it will redirect to show last post you entered,

I was using redirect_to @post but that comes with error i stuck then i use redirect_to action: :show, id: @post.id

it's working when i create a new post then it redirect to /posts?id=last_inserted_id but as i saw other scaffold address should be posts/1 or etc and when i visit /posts it should show all the posts action defined as index in controller.

routes.rb

<code>
  Blog::Application.routes.draw do
  root "welcome#new"

  resource :posts
</code>

Controller :

class PostsController < ApplicationController


  def index
    @post = Post.all
    respond_to do |format|
      format.html #index.html.erb
    end
  end

  def show
    @post = Post.find(params[:id])
    respond_to do |format|
      format.html #show.html.erb
    end
  end

  def new

  end

  def create
    @post = Post.new post_params
    @post.save
    redirect_to action: :show, id: @post.id
  end

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

Thanks

Upvotes: 2

Views: 2907

Answers (1)

gotva
gotva

Reputation: 5998

You should use resources :posts not resource!

resources generates "full" CRUD - 7 actions http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resources

when resource generates routes uniq resource (without action show) http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Resources.html#method-i-resource

Upvotes: 1

Related Questions