Faster Database Where For Rails Availability Calendar
Solution 1:
What Robbie is describing is capturing the data in bulk to present it in a second pass. You can do this:
@reservations = Reservations.where(bed_id: [ ... ], date: (from..to)).group_by do |r|
[r.bed_id, r.date]
endWhere this returns a singular structure that should contain all the reservations in a way that can be easily indexed using both bed_id and a date. You can turn this into a two-tier structure if necessary, but it's usually not.
When iterating:
- current_user.beds.each do |bed|
- reservation = @reservations[[bed.id,date]]
- if reservation
# ...
This practice of selectively, but aggressively eager-loading records usually works quite well when you're dealing with complex inter-dependencies that can't be easily expressed with an includes(..) element in your loading chain.
Also, remember in Ruby there's only two things that are logically false: literal false and nil. Everything else evaluates as logically true, including 0, empty strings, arrays and hashes. As such comparisons != nil are almost always extraneous and confusing, especially if you do double-negation like unless (x != nil).
If you're looking to be able to resolve a number of arbitrary date+bed pairs against the database you could make some kind of booking key that was a combination of date and bed_id then it'd be a lot easier to scan for these. You could do a WHERE booking_token IN (...) and have it all indexed, performant, and concise. It takes some advance planning though to do it properly. YYYY-MM-DD-bed_id could work as a first pass.
Solution 2:
For your view code, I would try:
= week_calendar events: @monthly_reservations, attribute: :datedo |date, appts|
- current_user.beds.each do |bed|
%p{style: "border: 1px solid black; padding: 5px; font-size: 10px;"}
= [bed.name, @reservations[[date, bed.id]]].compact.join(":")
Post a Comment for "Faster Database Where For Rails Availability Calendar"