Api :: V1 :: PostsController#show中的ActiveRecord :: RecordNotFound

时间:2014-07-25 20:34:51

标签: ruby-on-rails json angularjs activerecord rails-api

我正在尝试从egghead.io跟踪Rails Todo API第1部分https://egghead.io/lessons/angularjs-rails-todo-api-part-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

配置/ 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}

1 个答案:

答案 0 :(得分:3)

在routes.rb

中设为resources :posts

因为你有错误的路线并且正在调用show方法而不是索引方法