Kathan Kathan - 22 days ago 6
Ruby Question

Records where boolean true for each element of array - Rails 4

Using rails 4.

I have a

Spot
model with 7 boolean attributes for each day of the week:
monday:boolean
,
tuesday:boolean
,
wednesday:boolean
etc.

Users should be able to select a date range, and have only the spots that are available on those days be returned.

Currently having trouble setting up the class method that finds the correct records.

So far, I am creating a range from the dates the user enters, which returns all days of the week in that range.

range_array = (start_date..end_date).to_a.map{ |date| date.strftime("%A").downcase }
=> ["wednesday", "thursday", "friday"]


And here's where I am getting stuck. I am trying to find all spots where the boolean field corresponding to the element in the array is true. So in the example above, I would like to form this query
Spot.where(wednesday: true, thursday: true, friday: true)


Is doing something like this possible? Is there a better/different way? Maybe I am going about this wrong. Thanks for any help/suggestions.

Update (for Andrey)...
Spot.first
example instance:

=> #<Spot id: 18, address: "4640 east skyline", title: "iodjiojoidj", description: "<p>jijiojfojewoif</p>\r\n",
created_at: "2016-03-30 04:54:07",
updated_at: "2016-09-26 05:39:51",
user_id: 13, timezone: nil,
surge_pricing: nil, free: nil, monday: true,
tuesday: true, wednesday: true, thursday: false,
friday: false, saturday: false, sunday: false>

Answer

Using your range_array, you should be able to do your query as follows:

query = range_array.inject({}) do |h, e|
          h[e] = true
          h
        end

Spot.where(query)