0

私はegghead.io https://egghead.io/lessons/angularjs-rails-todo-api-part-1からRails Todo APIパート1に従おうとしています

localhost:3000/api/v1/posts にアクセスしようとしていますが、ページには次の json 応答が表示されます。

[]

しかし、代わりにエラーが発生します:

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

また、そのレコードの json 応答を返すレコードを追加しようとしましたが、同じエラーが発生します。私は何を間違っていますか?

次のようにコントローラーとルートを完成させました。

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

レーキルート:

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}
4

1 に答える 1

3

resources :postsあなたのroutes.rbでそれを作ってください

そのままでは、不正なルートがあり、index メソッドの代わりに show メソッドが呼び出されています。

于 2014-07-25T20:40:00.580 に答える