Reputation: 119
Class Business
has a hash field hours
that looks like this:
{
monday:
{
open_hour: 9,
open_min: 0,
close_hour: 17,
close_min: 45
}
tuesday:
...
}
My desired query looks like this:
Business.where(:'hours.monday.close_hour'.lt => 23)
which is functional in and of itself.. However, I'd like to pass monday
in as a variable day
, ie.
Business.where(:'hours.[day].close_hour'.lt => 23)
Is there a good way to do this? Note that this is part of a larger query chain that must return a Mongoid::Criteria
object.
Upvotes: 1
Views: 355
Reputation: 119
Ultimately we came up with this:
query = { :"hours.#{day}.close_hour" => { '$lt' => 23 } }
Business.where(query)
Source: How to use a variable as a field name in mongodb-native findOne()?
Thanks!
Edit: I'd like to point out that user 'mu is too short' recognised that it can just as easily be written like this:
:"hours.#{day}.close_hour".lt => 23
which is much closer to our original intent.
Upvotes: 3