*重写了整个问题,以便更清楚......
这就是我的表格的样子(没有无用的列) 我用pgadmin
生成了这个
SELECT
notifications.id
FROM
activities,
notifications,
comments
WHERE
activities.trackable_id = comments.id AND
notifications.activity_id = activities.id;
使用pgadmin,此查询会给出正确的结果。
我不知道如何使用包含(或者可能是连接)将3个表作为上面的sql。
我的尝试
@notifications = current_user.notifications.includes(:activity, :comments).where("activities.trackable_id = comments.id AND notifications.activity_id = activities.id")
不富有成效
答案 0 :(得分:1)
默认情况下,当您传递ActiveRecord :: Base#join一个命名关联时,它将使用可能的主键执行INNER JOIN。正如我们在模型中看到的那样,id不是默认方式,因此您可以区分将使用哪个键来加入joins
方法中的表。有点像这样:
@notifications = current_user.notifications.
joins("INNER JOIN activities ON notifications.activity_id = activities.id").
joins("INNER JOIN comments ON activities.trackable_id = comments.id")