雖然我有ID 13163(db.locations.find({_id: 13163})
)的記錄,這是給我的錯誤:雖然我已經在數據庫中的記錄,它給「Mongoid ::錯誤:: DocumentNotFound」
Mongoid ::錯誤:: DocumentNotFound在LocationsController#顯示
Problem: Document(s) not found for class Location with id(s) 13163. Summary: When calling Location.find with an id or array of ids, each parameter must match a document in the database or this error will be raised. The search was for the id(s): 13163 ... (1 total) and the following ids were not found: 13163. Resolution: Search for an id that is in the database or set the Mongoid.raise_not_found_error configuration option to false, which will cause a nil to be returned instead of raising this error when searching for a single id, or only the matched documents when searching for multiples.
# Use callbacks to share common setup or constraints between actions.
def set_location
@location = Location.find(params[:id])
end
locations_controller.rb:
class LocationsController < ApplicationController
before_action :set_location, only: [:show, :edit, :update, :destroy]
# GET /locations
# GET /locations.json
def index
@locations = Location.all
end
# GET /locations/1
# GET /locations/1.json
def show
end
private
# Use callbacks to share common setup or constraints between actions.
def set_location
@location = Location.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def location_params
params.require(:location).permit(:loc_name_en, :loc_name_jp, :channel)
end
end
設置選項raise_not_found_error: false
不是這種情況,因爲我在數據庫中有文檔。
SOLUTION:
非常感謝@mu is too short給我一個提示。
該問題可以通過兩種方式來解決:
- 聲明
field :_id, type: Integer
在模型location.rb
- 或者路過參數轉換爲整數像
locations_controller.rb
Location.find(params[:id].to_i)
如@mu下面所示太短的回答
另一種解決方案是聲明模型中字段的類型* location.rb *:'field:_id,type:Integer' – Askar
@oscar:對,我甚至沒有想到這一點。你可以把它作爲一個答案,它可能比「to_i」到處都更有用。 –