Given the following models:
class Room < ActiveRecord::Base
has_many :contracts
end
class Contracts < ActiveRecord::Base
# columns
# start_date Date
# end_date Date
belongs_to :room
end
The contracts of one room are not overlapping. My question is, how i am be able to find gaps between contracts. An Example:
room = Room.create
c1 = room.contracts.create(:start_date => Date.today, :end_date => 1.month.since)
c2 = room.contracts.create(:start_date => 2.months.since, :end_date => 4.months.since)
rooms = Room.with_contract_gaps #rooms == [room]
The bonus round would be the possibility to search for gaps with a specific date-range or even better to fetch all gaps as date-ranges in as hash or array.
gaps = Room.contract_gaps
gaps # {1 => [((1month.since+1.day)..(2.months.since-1.day))]}
I have already searched via google and found Inverting Date Ranges. But i have honestly not really an idea, how i can use it in this specific case.
It would be great if someone has a solution or some helpful tips to solve this problem.