Reputation: 6732
I am trying to follow Rails Todo API Part 1 from egghead.io https://egghead.io/lessons/angularjs-rails-todo-api-part-1
I am trying to access localhost:3000/api/v1/posts and the page should show the json response of:
[]
but instead I get the error:
ActiveRecord::RecordNotFound in Api::V1::PostsController#show
Couldn't find Post without an ID
def show
respond_with(Post.find(params[:id])) <----- error is here
end
I also tried adding a record which should return the json response of that record but I get the same error. What am I doing wrong?
I have completed the controller and routes as follows:
app/controllers/api/v1/posts_controller.rb
module Api
module V1
class PostsController < ApplicationController
skip_before_filter :verify_authenticity_token
respond_to :json
def index
respond_with(Post.all.order("id DESC"))
end
def show
respond_with(Post.find(params[:id]))
end
def create
@post = Post.new(post_params)
if @post.save
respond_to do |format|
format.json {render :json => @post}
end
end
end
def update
@post = Post.find(params[:id])
if @post.update(post_params)
respond_to do |format|
format.json {render :json => @post}
end
end
end
def destroy
respond_with Post.destroy(params[:id])
end
private
def post_params
params.require(:post).permit(:content)
end
end
end
end
config/routes.rb
WhatRattlesMyCage::Application.routes.draw do
namespace :api, defaults: {format: :json} do
namespace :v1 do
resource :posts
end
end
end
rake routes:
Prefix Verb URI Pattern Controller#Action
api_v1_posts POST /api/v1/posts(.:format) api/v1/posts#create {:format=>:json}
new_api_v1_posts GET /api/v1/posts/new(.:format) api/v1/posts#new {:format=>:json}
edit_api_v1_posts GET /api/v1/posts/edit(.:format) api/v1/posts#edit {:format=>:json}
GET /api/v1/posts(.:format) api/v1/posts#show {:format=>:json}
PATCH /api/v1/posts(.:format) api/v1/posts#update {:format=>:json}
PUT /api/v1/posts(.:format) api/v1/posts#update {:format=>:json}
DELETE /api/v1/posts(.:format) api/v1/posts#destroy {:format=>:json}
Upvotes: 0
Views: 625
Reputation: 36860
Make it resources :posts
in your routes.rb
As it is you have malformed routes and the show method is being called instead of the index method
Upvotes: 3