ruby-on-rails 确定延长预订时是否有可用的预订项目

owfi6suc  于 2023-04-08  发布在  Ruby
关注(0)|答案(1)|浏览(140)

我遇到了一个问题,一个用户在我的tool借用应用程序中编辑他们的reservation。特别是当user想要相同的工具,但需要在他们当前的reservation之前几小时/几天取到它和/或在几小时/几天后归还它。
例如,用户具有

{ 
  tool: "impact wrench", 
  pickup_at: 05-06-2023 8:00 AM, 
  return_at: 05-07-2023 6:00 PM 
}

但是想要

{
  tool: "impact wrench", 
  pickup_at: 05-05-2023 8:00 AM, 
  return_at: 05-08-2023 2:00 PM 
}

确定工具是否可用的一种方法是检查从new pickup_atold pickup_at的冲击扳手是否可用,然后检查从old return_atnew return_at的冲击扳手是否可用。

a = Tool.reservations.where("tool_id = ? and pickup_at <= ? and return_at >= 2", 
       t_id, new_pickup_at, current_pickup_at).any?

b = Tool.reservations.where("tool_id = ? and pickup_at <= ? and return_at >= 2", 
       t_id, current_return_at, new_return_at).any?

tool_available = a & b

有没有{更好的|首选|更有效的方法?

7cwmlq89

7cwmlq891#

如果你已经有了当前reservation的示例或ID,你可以通过在SQL语句中排除该reservation来只执行一个查询。比如:

reserved = Tool.reservations.where("tool_id = ? AND pickup_at <= ? AND return_at >= ? AND id != ?", 
   tool_id, new_pickup_at, new_return_at, current_reservation.id).any?

tool_available = !reserved

相关问题