2016-04-29 102 views
0

看到許多與此相關的問題,但沒有一個答案給我的問題。 我有沒有ActiveRecord支持的Rails API應用程序。很容易重現問題。按照步驟: 沒有ActiveRecord的支持創建軌API網站沒有路線匹配{:action =>「show」...缺少必需的鍵:[:id]

rails new test001 -O --api 

更改文件夾test001並運行:

rails g scaffold testapp id name 

創建在app/models文件夾的模型文件testapp.rb

class Testapp 
    include ActiveModel::Model 
    attr_accessor :id, :name, :created_at, :updated_at 
    def self.all 
    t1 = Testapp.new(:id =>111, name: "t111") 
    return [t1] 
    end 
end 

啓動服務器

rails s 

使用郵遞員REST客戶端創建GET請求

http://localhost:3000/testapps.json 

它失敗,錯誤ActionView::Template::Error (No route matches {:action=>"show", :controller=>"testapps", :format=>:json, :id=>#<Testapp:0x00000005411518 @id=111, @name="t111">} missing required keys: [:id]):

我有POST虛擬實現,PUT,GET 1項,所有的作品。這裏是虛擬實現GET 1項(/testapps/x.json)

def self.find(p) 
    return Testapp.new(:id =>p, name: "t123") 
    end 

什麼是讓所有(/testapps.json)的問題?

+0

爲了驗證可能的答案,如果您可以發佈您的'routes.rb'文件或該文件的特定部分,其中您爲'testapps'設置了路由控制器。 –

+0

'Rails.application.routes.draw do resources:testapps end' 正如我所說的,所有其他的作品。 –

+0

@ craig.kaminsky 您可以從[dropbox]下載應用程序(https://dl.dropboxusercontent.com/u/10850412/test001.zip) –

回答

1

找到解決辦法。 問題是支架產生index.json.jbuilder 文件:

json.array!(@testapps) do |testapp| 
    json.extract! testapp, :id, :id, :name 
    json.url testapp_url(testapp, format: :json) #REMOVE 
end 

它補充線json.url testapp_url(testapp,格式::JSON)無故。 json.extract!已反序列化的對象。 刪除行解決的問題。 我仍然不知道爲什麼testapp_url(testapp,format:json)導致錯誤。檢查導軌路由文檔http://guides.rubyonrails.org/routing.html

相關問題