【问题标题】:Ransack searching for instances with specific value in last of has_many associationsRansack 在最后一个 has_many 关联中搜索具有特定值的实例
【发布时间】:2018-02-15 06:26:23
【问题描述】:

我在我的 rails 项目中使用ransack gem 进行排序和过滤。

有一个Child 模型,它有许多课程订阅。 Courseperiod_idChild 有一个方法 last_subscription_period。 很高兴能回答以下任何问题:

  1. 使用 ransack 在此方法结果上过滤子项的方法是什么?
  2. 用于选择具有特定 period_id 的最后订阅的孩子的 SQL 查询是什么?

型号:

Child has_many subscriptions
Subscription belongs_to child
Subscription belongs_to course

children: id
subscriptions: child_id, course_id, created_at
courses: period_id

【问题讨论】:

标签: mysql sql ruby-on-rails ransack


【解决方案1】:
SELECT l.child_id, co.period_id
FROM (
    SELECT s.child_id, s.course_id
    FROM (
        SELECT child_id, MAX(created_at) AS latest_subscription
        FROM subscriptions
        GROUP BY child_id
    ) AS l
    JOIN subscription AS s
        ON s.child_id = l.child_id
        AND s.created_at = l.latest_subscription
) AS l
JOIN courses AS co
ON co.id = l.course_id

【讨论】:

  • 我最终用这个查询做了一个洗劫者。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2019-05-21
  • 2014-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多