Boenne Boenne - 3 months ago 30
Ruby Question

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

I am querying a model in my controller with the following code:

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

The model is defined correctly, the params are present. However, instead of returning an instance of UserForecast, it returns an instance of Mongoid::Criteria.

This line


results in the following error:

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

I have no clue what is happening.


That's what Mongoid's where does: it builds a query represented as a Mongoid::Criteria object. ActiveRecord does the same thing and the solutions are the same:

  1. Use first/last/... to grab just one result from the query:

    @user_forecast = UserForecast.where(...).first
  2. Better, use find_by to find exactly one if you're expecting there to be only one:

    @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)