【问题标题】:ActiveRecord::RecordNotFound in Api::V1::PostsController#showApi::V1::PostsController#show 中的 ActiveRecord::RecordNotFound
【发布时间】:2014-07-25 20:34:51
【问题描述】:

我正在尝试关注 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}

【问题讨论】:

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


    【解决方案1】:

    在你的 routes.rb 中设置为 resources :posts

    因为你的路由格式不正确,所以调用的是 show 方法而不是 index 方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多