Rails中修改leave_day方法实现今日至未来3天审批假天数统计
Got it, let's work through this problem. The issue with your initial range approach is that your original method checks if a single date falls within a leave's interval—but when you want to capture any leave that overlaps with a date range (today to 3 days from now), you need to check for interval overlap instead of a single date match.
First, Clarify Your Requirement
There are two common interpretations here, so let's cover both:
1. Count the number of approved leave records that overlap with today to 3 days from now
This counts each leave once if it's active at any point in your target range. Use this query:
def self.leave_day target_start = Date.today target_end = Date.today + 3.days self.where(status: "Approved") .where("start_date <= ? AND end_date >= ?", target_end, target_start) .count end
Why this works: For two intervals (leave's start_date/end_date and your target_start/target_end) to overlap, the leave's start must be before or equal to your range's end, and the leave's end must be after or equal to your range's start. This catches all leaves that are active at any point during your target window.
2. Calculate the total number of leave days covered in the target range
If you need to sum up the actual days each approved leave overlaps with your target range (e.g., a leave spanning 4 days that overlaps with 3 of your target days contributes 3 to the total), use this:
def self.total_leave_days target_start = Date.today target_end = Date.today + 3.days approved_leaves = self.where(status: "Approved") .where("start_date <= ? AND end_date >= ?", target_end, target_start) approved_leaves.sum do |leave| # Find the overlapping portion of the leave and target range overlap_start = [leave.start_date, target_start].max overlap_end = [leave.end_date, target_end].min # Calculate the number of days in the overlap (overlap_end - overlap_start + 1).to_i end end
Why Your Initial Range Approach Failed
Using something like where(start_date: (Date.today+1)..(Date.today+3.days)) would only find leaves that start within that range—not leaves that started earlier but are still active, or end later but started in the range. The interval overlap condition we used above covers all those edge cases.
内容的提问来源于stack exchange,提问作者fahad

