3

虽然我有 id 为 13163 ( db.locations.find({_id: 13163})) 的记录,但它给了我错误:

Mongoid::Errors::DocumentNotFound in LocationsController#show

问题:找不到 ID 为 13163 的 Location 类的文档。 摘要:当使用 ID 或 ID 数组调用 Location.find 时,每个参数必须与数据库中的文档匹配,否则将引发此错误。搜索 id(s):13163 ...(共 1 个),但未找到以下 id:13163。解决方法:搜索数据库中的 id 或将 Mongoid.raise_not_found_error 配置选项设置为 false,这将导致在搜索单个 id 时返回 nil 而不是引发此错误,或者在搜索多个时仅返回匹配的文档。

# Use callbacks to share common setup or constraints between actions.
def set_location
  @location = Location.find(params[:id])
end

位置控制器.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并非如此,因为我在数据库中有一个文档。


解决方案:

非常感谢@mu 太短了,无法给我提示。

该问题可以通过两种方式解决:

  1. field :_id, type: Integer在模型中声明location.rb
  2. 或者将传递参数转换为 Integer 如下所示Location.find(params[:id].to_i)@mu的答案太短locations_controller.rb
4

1 回答 1

3

我猜你有类型问题。你这样说:

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

在 MongoDB shell 中查找文档。这意味着您在locations集合中有一个文档,其_idnumber 13163。如果你使用字符串'13163':

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

你不会找到你的文件。in 的值params[:id]可能是一个字符串,所以你说:

Location.find('13163')

当你想说:

Location.find(13163)

如果_id真的是一个号码,那么你需要确保你find用一个号码打电话:

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

您可能会感到困惑,因为有时 Mongoid 会在Strings 和Moped::BSON::ObjectIds 之间转换(有时不会),所以如果您_id是通常的 ObjectId,您可以说:

Model.find('5016cd8b30f1b95cb300004d')

并且 Mongoid 会为您将该字符串转换为 ObjectId。Mongoid 不会为您将 a 转换String为数字,您必须自己执行此操作。

于 2014-12-21T06:20:58.507 回答