虽然我有 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 太短了,无法给我提示。
该问题可以通过两种方式解决:
field :_id, type: Integer
在模型中声明location.rb
- 或者将传递参数转换为 Integer 如下所示
Location.find(params[:id].to_i)
@mu的答案太短locations_controller.rb