Reputation: 616
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
logger.debug @user_forecast.id
results in the following error: `
NoMethodError (undefined method `id' for #<Mongoid::Criteria:0x00000004caa108>):
I have no clue what is happening.
Upvotes: 0
Views: 1286
Reputation: 434665
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:
Use first
/last
/... to grab just one result from the query:
@user_forecast = UserForecast.where(...).first
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)
)
Upvotes: 1