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 响应,但我得到了同样的错误。我究竟做错了什么?

我已经完成了控制器和路由如下:

应用程序/控制器/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

配置/路由.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 中

因为它是您的路线格式错误,并且正在调用 show 方法而不是 index 方法

于 2014-07-25T20:40:00.580 回答