首页 > 解决方案 > ActiveRecords,我通过提供其他表的 id 过滤值

问题描述

我在弄清楚如何完成特定查询时遇到问题。

我正在尝试获取日期在其他两个日期之间的所有行(这两个日期是表中的列)。问题是这些日期都是与另一个表相关联的 ID(外键)。

两个表的结构是:

**ReservationDate**

 - id
 - date (which is the date)

**Reservation**

 - id
 - from_date_id
 - to_date_id

如果他们不是日期表的 id,我会简单地完成

Reservation.where("(?) BETWEEN from_date AND to_date",date)

但是,它们是 ReservationDate 表的 id,我无法找到一种方法来做到这一点。

理想情况下,类似的东西会起作用。但事实并非如此。

Reservation.where("(?) BETWEEN from_date_id.date AND to_date_id.date",date)

标签: sqlruby-on-railsrubysqliteactiverecord

解决方案


You'll need to join the tables to query them:

Reservation.
  joins(
    'reservation_dates AS from_dates ON reservations.from_date_id = from_dates.id').
  joins(
    'reservation_dates AS to_dates ON reservations.to_date_id = to_dates.id').
  where('(?) BETWEEN from_dates.date AND to_dates.date', date)

I'm curious though, what is the point of the reservation_dates table?


推荐阅读