我正在使用PublicActivity gem:https://github.com/pokonski/public_activity
我使用PublicActivity跟踪的所有模型都使用列edition_id
。而且我想知道如何通过该列来确定范围,因为它具有多态关系。
例如PublicActivity看起来像这样:
PublicActivity::Activity.limit(50)
+----+--------------+----------------+----------+------------+--------------------+------------+--------------+----------------+---------------------------+---------------------------+
| id | trackable_id | trackable_type | owner_id | owner_type | key | parameters | recipient_id | recipient_type | created_at | updated_at |
+----+--------------+----------------+----------+------------+--------------------+------------+--------------+----------------+---------------------------+---------------------------+
| 1 | 42 | QuizMaster | 6 | User | quiz_master.update | {} | | | 2013-04-12 17:33:14 +0100 | 2013-04-12 17:33:14 +0100 |
| 2 | 25 | Place | 6 | User | place.update | {} | | | 2013-04-12 17:42:42 +0100 | 2013-04-12 17:42:42 +0100 |
| 3 | 25 | Event | 6 | User | event.update | {} | | | 2013-04-12 17:45:08 +0100 | 2013-04-12 17:45:08 +0100 |
| 4 | 20 | QuizMaster | 6 | User | quiz_master.update | {} | | | 2013-04-12 17:49:09 +0100 | 2013-04-12 17:49:09 +0100 |
| 5 | 20 | QuizMaster | 6 | User | quiz_master.update | {} | | | 2013-04-12 17:50:51 +0100 | 2013-04-12 17:50:51 +0100 |
+----+--------------+----------------+----------+------------+--------------------+------------+--------------+----------------+---------------------------+---------------------------+
其中edition_id是多态可跟踪关系。
我想做的事情如下:
PublicActivity::Activity.limit(50).includes(:trackable)# where trackable edition = 1
我不确定如何或者甚至可以在多个"可跟踪的"中加入或包含或预加载多态模型。类型。
答案 0 :(得分:2)
由于多态性,我认为这不可能直接用SQL,但你可以很容易地用ruby做点什么。
PublicActivity::Activity.limit(50).select {|c| c.trackable.edition_id = 1 }
它不如SQL查询有效,但使用Rails preload
它可能已经足够好了,具体取决于你提取的记录数。
PublicActivity::Activity.limit(50).preload(:trackable).select {|c| c.trackable.edition_id = 1 }