【问题标题】:How do I write a Ruby where clause with dates and array lookup?如何编写带有日期和数组查找的 Ruby where 子句?
【发布时间】:2025-12-27 16:15:10
【问题描述】:
local_appointment_records = ExternalAppointment.where(external_id: appointment_ids, deleted_by: nil, ('start_time BETWEEN ? AND ?',@date_from, @date_to) )

我想做类似上面的事情。 我首先要检查模型外部ID是否在约会ID数组中,然后确保它没有被软删除,然后检查记录开始时间是否在日期之间。 非常感谢任何帮助。

【问题讨论】:

    标签: sql ruby-on-rails where-clause


    【解决方案1】:

    您不需要使用 SQL 字符串来创建该查询。只需使用一个范围:

    local_appointment_records = ExternalAppointment.where(
      external_id: appointment_ids, 
      deleted_by: nil, 
      start_time: @date_from..@date_to
    )
    

    如果你想使用 SQL 字符串,你想链接调用:

    local_appointment_records = ExternalAppointment.where(
      external_id: appointment_ids, 
      deleted_by: nil
    ).where(
      'start_time BETWEEN ? AND ?', @date_from, @date_to
    )
    

    【讨论】:

    • 附带说明 - 如果 appointment_ids 实际上是从数据库中获取的东西,您实际上可以传递一个 ActiveRecord::Relation 并让 ActiveRecord 组成一个子查询。