我想计算离开 b/w 状态被批准的两个日期

I want to calculate leaves b/w two dates where status is approved

 def calculate_availed_leave
  if self.saved_change_to_status? && self.status == "Approved"
   leave_start_date = self.start_date
   leave_end_date = self.end_date
   leave_date = []
   taken_leaves = Leave.includes(:employee).where(status: "Approved" ).where(start_date:leave_start_date..leave_end_date)
   taken_leaves.each do |leave|
     leave_date =   leave.end_date - leave.start_date  
   end
  availed_leaves = self.employee.allowed_leaves - leave_date
  self.employee.update(availed_leaves: availed_leaves)
end

我想计算休假 b/w 状态被批准的两个日期,但我不知道该怎么做

您的代码有几个问题:

  • taken_leaves 的范围不限于单个员工:您正在为 所有 名员工
  • 遍历叶子
  • leave_date 被多次覆盖。初始值 ([]) 从未使用过,each 块中设置的任何值也未使用(直到最后一个)。然后该值用于更新 employee.availed_leaves.

简而言之,您通过仅查看一个休假(可能属于另一名员工)而不是查看仅属于该员工的所有休假来更新员工的 availed_leave

假设您的 Employee 模型定义中有 has_many :leaves,您可以像这样重写此代码:

leave_taken = employee.leaves.
  select('leaves.*, (leaves.end_date - leaves.start_date) AS duration').
  where(status: 'Approved', start_date: start_date..end_date)

available_leaves = employee.allowed_leaves - leave_taken.sum(:duration)

注意:除非您要覆盖 Leave 模型上的属性以产生副作用,否则您不需要当前代码中的所有 self.