How to search by duration in Algolia

Say I'm building a hotel booking platform, and each room record has an availability calendar. A common search criterion is duration search. When the user enters a start date and an end date, and the database selects rooms that are not occupied with this duration.

I implemented a very naive approach when I store busy days as an array of days.

attribute :occupied_at_i do array = [] if !occupied_at.empty? occupied_at.each do |date| array << Time.parse(date).to_i end end array end 

And then on the client side, I add the following javascript code to cross check if the day is in numericRefinement

 // Date Filters $('.date-field') .on('change', function() { if(_.every(_.map($('.date-field'), function(date) {return _.isEmpty(date.value) }), function(n) {return n==false;})) { helper.clearRefinements('occupied_at_i'); var arrayOfDates = addDateFilters(); _.forEach(arrayOfDates, function(n) { helper.addNumericRefinement('occupied_at_i', '!=', n); }); showClearAllFilters(); helper.search(); } }); 

So, this is obviously not a very good way to do this, I wonder what is better to use on algolia and search by duration?

thanks

+7
javascript ruby-on-rails search algolia
source share
1 answer

Hope this helps others (as the question has long been asked)

it is always better to perform server-side filtering and display the results. Here's one approach - add datetime fields to the room model as start_date and end_date . Thus, when the user enters a start date and an end date, the entries are selected based on the busy state for that duration. One simple query would look like this:

 Room.where.not("start_date >= ? AND end_date <= ?", start_date, end_date) 

Another best solution would be to have another model for storing data about numbers with start and end datetime fields. Thus, we can have several orders for rooms in a certain room, and they can be stored simultaneously in the room reservation collection. Therefore, the query will look like this:

 Room.left_joins(:room_bookings). where( "room_bookings.start_date > ? OR room_bookings.end_date < ?", end_date, start_date ) 
0
source share

All Articles