简体   繁体   中英

Search free term in RoR

I am looking for a way to write a query that would look for the date of the conference room in which it is free. I have two tables: A table with the names of conference rooms and The booking table consists of two fields: start date [date_from] and end date [date_end]

A new client looking for a conference room first types in the search engine the day of renting the room and the ending day. How to search the registration table to take into account the days booked between those days and display only those conference rooms that are free.

For example, the schedule of the room No. 1 is reserved in the table from March 6, 2018 to March 8, 2018 and room No. 2 from March 4, 2018 to March 7, 2018. I am looking for the room from March 8, 2018 to March 9, 2018

What ways do you suggest?

Assuming model names as ConferenceRoom & ConferenceBooking, hence the corresponding tables will be like conference_rooms & conference_bookings. Once the date_from and date_end parameters are provided, the query would be look like

ConferenceRoom.
  left_joins(:conference_bookings).
  where(
    "conference_bookings.date_from > ? OR 
     conference_bookings.date_end < ?", date_end, date_from
  )

The query fetch results of conference room which has booking end dates less than provided date_from value and conference room which has booking start dates greater than provided date_end value.

First get all ids from rooms that are booked during the date range.

ids = Booking.where("date_from <= ? AND date_end >= ?", date_end, date_from).pluck(:room_id)

All other rooms are free:

free_rooms = Room.where.not(id: ids)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM