我有一个users
表,一个notifications
表和一个notification_reads
的连接表。我正在尝试为ActiveRecord查询编写一个范围,该范围将返回所有通知(Notification.all
),并根据用户是否具有该通知的相关notification_read来附加字段。
我想象它看起来像是:
class Notification
scope :with_reads_by_user, -> (user) {
select("*", "[some sql that produces a boolean] as read")
.joins(:notification_reads)
.where(notification_reads: {user: user})
}
end
尽管如此,我所尝试过的任何事情似乎都没有结束。
答案 0 :(得分:1)
尝试下面的一个,
scope :by_user, lambda { |user|
joins("LEFT OUTER JOIN notification_reads ON notification_reads.user_id = ? and notification_reads.notification_id = notifications.id", user.id).select("*", "IF(notification_reads.user_id IS NULL, FALSE, TRUE) as is_read_by_user")
}
查询
Notification.by_user(current_user)
参考:select column as true / false if id is exists in another table
P.S:没试过这个。