我正在嘗試使用僅僅是API應用程序的Mongodb來構建Rails後端。我有一個事件模型和API控制器,當我去到localhost:3000 /事件/ 2,我得到一個404錯誤,雖然我知道的紀錄是在我的數據庫:無法在使用Mongodb的Rails中擊中API端點
{ "_id" : 2, "name" : "String Cheese", "location" : "Durham, NC", "price" : "40.00" }
我的控制器看起來像這樣:
class API::V1::EventsController < ApplicationController
respond_to :json
def show
respond_with Event.find('_id')
end
private
def event_params
params.require(:event).permit(:name, :url, :location, :dates, :price, :info, :genre, :address, :city, :tags)
end
end
我的路線是這樣的:
require 'api_constraints'
Rails.application.routes.draw do
namespace :api, defaults: { format: :json }, path: '/' do
scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
resources :users, only: [:show]
resources :events, only: [:show]
end
end
end
然後,我在我的lib文件夾中的api_constraints.rb,看起來像這樣:
class ApiConstraints
def initialize(options)
@version = options[:version]
@default = options[:default]
end
def matches?(req)
@default || req.headers['Accept'].include?("application/vnd.marketplace.v#{@version}")
end
end
這是爲了消除在uri中擁有api版本號的需要。我不確定它是否影響我的終端。
所以後來當我開始我的服務器和去localhost:3000/events/2
我得到一個404錯誤:
{ 「地位」:404, 「錯誤」: 「未找到」, 「異常」:「#\ u003cMongoid: :Errors :: DocumentNotFound:\ nmessage:\ n找不到具有ID(s)的類Event的文檔{\「_ id \」= \ u003e \「2 \」}。\ nsummary:\ n當調用Event時。使用id或id數組查找每個參數必須與數據庫中的文檔相匹配,否則將引發此錯誤。搜索的是id(s):{\「_ id \」= \ u003e \「2 \」}
堆棧跟蹤實際上甚至更長,所以如果有人需要它,我可以發佈整個東西。
任何幫助將不勝感激。
默認情況下,Mongoid將標識存儲爲「BSON :: ObjectId」 - 不是字符串。 https://docs.mongodb.com/ruby-driver/master/tutorials/6.0.0/mongoid-documents/ – max