0

我正在寻找对我的应用程序中的活动对象进行查询。我正在使用public_activitygem,我有一个与多个模型相关的活动列表,我想列出最近的独特活动。

基本上我想查询特定跟踪的最新活动。假设我正在跟踪like 按钮,它ID29。我想查询最近的(一个)跟踪实例ID=29和其他跟踪 ID。我不太清楚查询rails。现在这是我唯一显示所有活动的行:

@activities = PublicActivity::Activity.order("created_at desc").where(owner_id: current_user.id)

假设我有一张活动表,如下所示:

id  activity_id description created_on
1   3           Like        yesterday
2   3           Unlike      two days ago
3   6           Comment     yesterday
4   7           Review      yesterday
5   7           Review      two days ago

我想将每个活动 ID 的最新条目提取到@activities变量中,如下所示:

id  activity_id description created_on
1   3           Like        yesterday
3   6           Comment     yesterday
4   7           Review      yesterday

public_activity有解决方法吗?

4

1 回答 1

0

您可以使用group和的组合select来完成此操作。

PublicActivity::Activity.
  select("MAX(created_at) as when, trackable_type").
  group("trackable_type").
  where(owner_id: current_user.id)

这是输出

+-------------------------+-------------------------+
| trackable_type          | when                    |
+-------------------------+-------------------------+
| Report                  | 2015-11-27 20:25:31 UTC |
| QuickAnswer             | 2016-01-04 23:36:21 UTC |
| Comment                 | 2015-10-23 15:35:32 UTC |
| TakenExam               | 2016-01-04 23:46:11 UTC |
| SeenVideo               | 2015-08-23 21:27:58 UTC |
| Provider                | 2015-09-17 23:47:40 UTC |
| AnswerForRecommendation | 2015-08-18 15:13:03 UTC |
| Subscription            | 2015-08-24 08:37:08 UTC |
+-------------------------+-------------------------+
于 2016-01-05T03:06:58.280 回答