2014-12-21 38 views
3

雖然我有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給我一個提示。

該問題可以通過兩種方式來解決:

  1. 聲明field :_id, type: Integer在模型location.rb
  2. 或者路過參數轉換爲整數像locations_controller.rbLocation.find(params[:id].to_i)@mu下面所示太短的回答

回答

3

我猜你有一個類型問題。你這樣說:

db.locations.find({_id: 13163}) 

在MongoDB shell中找到文檔。這意味着您在locations集合中有一個文檔,其_id號碼13163。如果您使用的字符串'13163「:

db.locations.find({_id: '13163'}) 

你不會找到您的文檔。在params[:id]值可能是一個字符串,所以你說:

Location.find('13163') 

當你想說:

Location.find(13163) 

如果_id真的是一個數字,那麼你就需要確保你調用find擁有多項:

Location.find(params[:id].to_i) 

你可能會感到困惑,因爲有時會Mongoid String S之間轉換和Moped::BSON::ObjectId S(有時也不會),所以如果您的_id是平時的ObjectId你可以說:

Model.find('5016cd8b30f1b95cb300004d') 

和Mongoid將這個字符串轉換成的ObjectId爲您服務。 Mongoid不會將String轉換爲您的號碼,您必須自己做。

+1

另一種解決方案是聲明模型中字段的類型* location.rb *:'field:_id,type:Integer' – Askar

+0

@oscar:對,我甚至沒有想到這一點。你可以把它作爲一個答案,它可能比「to_i」到處都更有用。 –

相關問題