Mongoid 'where' 查询返回 Mongoid::Criteria 而不是结果(#<Mongoid::Criteria 的未定义方法)

Mongoid 'where' query returning Mongoid::Criteria instead of result (undefined method for #<Mongoid::Criteria)

我正在使用以下代码查询控制器中的模型:

@user_forecast = UserForecast.where(forecast_id: user_forecast_params[:forecast_id] , project_role_id: user_forecast_params[:project_role_id])

模型定义正确,参数存在。但是,它没有返回 UserForecast 的实例,而是 returns Mongoid::Criteria.

的实例

这一行

logger.debug @user_forecast.id

导致以下错误: `

NoMethodError (undefined method `id' for #<Mongoid::Criteria:0x00000004caa108>):

我不知道发生了什么。

这就是 Mongoid 的 where 所做的:它构建一个表示为 Mongoid::Criteria 对象的查询。 ActiveRecord做同样的事情,解决方案也一样:

  1. 使用 first/last/... 从查询中只获取一个结果:

    @user_forecast = UserForecast.where(...).first
    
  2. 更好的是,如果您希望只有一个,请使用 find_by 准确找到一个:

    @user_forecast = UserForecast.find_by(
      forecast_id:     user_forecast_params[:forecast_id],
      project_role_id: user_forecast_params[:project_role_id]
    )
    @user_forecast = UserForecast.find_by(
      user_forecast_params.slice(:forcecast_id, :project_role_id)
    )