代码之家  ›  专栏  ›  技术社区  ›  yogi_bear

ActiveRecord查询关联

  •  1
  • yogi_bear  · 技术社区  · 7 年前

    我有一个带有许多时隙(from和to,都是datetime属性)的事件模型。

    假设我有以下事件

    -插槽2(往返:明天)

    事件2-插槽3(往返时间:昨天)

    现在我要说的是只做过去的事。-只是事件2。

    当我询问

    Event.joins(:time_slots).where('time_slots.to < ?', DateTime.current)
    

    我如何才能得到事件2,即只有在所有关联都为真的情况下,如果所有关联都为真而不是任何关联,则返回。

    编辑1

    结果应该是ActiveRecord::Relation,因为我需要对它执行进一步的操作。

    Event.joins(:time_slots)
      .public_send(filter_by)
      .search(params[:query])
      .sorted(direction)
      .page(params[:page])
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   matthewd    7 年前

    最短的拼写可能是:

    Event.where.not(id: TimeSlot.current_or_future.select(:event_id))
    

    在时间段上定义了作用域:

    scope :current_or_future, -> { where(to: DateTime.current..DateTime::Infinity) }
    
    推荐文章