Rails 范围按日期范围过滤 [英] Rails scope filter by date range

查看:42
本文介绍了Rails 范围按日期范围过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多与 rails 日期范围问题相关的问题,但我的问题稍微复杂一些.

There are many questions relate to rails date range problem but mine is a little more complicated.

我有两种模型:房屋和预订.一个房子有_许多预订.一个 Booking 有两个日期格式的属性:check_in 和 check_out.

I have two models: house and booking. A House has_many bookings. A Booking has two attributes in date format: check_in and check_out.

我想要实现的目标:给出一个有效的日期范围,显示在此范围内可用的所有房屋.详细说明:

What I want to achieve: Giving a valid date range, show all houses that are available during this range. In detail:

  • 范围的开始日期不应出现在任何预订中.
  • 范围的结束日期不应出现在任何预订中.
  • 开始和结束之间不应有任何预订.

这可以使用 rails 作用域来完成吗?

Can this be done using the rails scope?

更新:

我发现下面的代码可以检查重叠的范围日期间隔.

I found the code below that can check scope date interval that overlaps.

named_scope :overlapping, lambda { |interval| {
:conditions => ["id <> ? AND (DATEDIFF(start_date, ?) * DATEDIFF(?, end_date)) >= 0", interval.id, interval.end_date, interval.start_date]
}}

如何将其转移到我的问题中?

How can I transfer this to my problem?

推荐答案

scope :overlapping, (lambda do |start_date, end_date|
  House.includes(:bookings).where("bookings.check_in < ? AND bookings.check_out > ?", 
  start_date, end_date).references(:bookings).uniq
end)

我继续删除了 >=<= 操作符,取而代之的是 >< 以明确显示这些预订超出给定范围,但您可以根据需要调整它们!

I went ahead and deleted the >= and <= operators in favor of > and < to explicitly show these bookings being outside of the given range, but you can adjust them per your needs!

更新

将查询更改为使用 #includes 而不是 #joins,因为我们正在查询附加表.

Changed query to use #includes instead of #joins, since we're querying the attached table.

这篇关于Rails 范围按日期范围过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆