根据关系的存在将属性添加到ActiveRecord_Relation结果?

时间:2016-11-01 06:02:30

标签: mysql ruby-on-rails activerecord

我有一个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

尽管如此,我所尝试过的任何事情似乎都没有结束。

1 个答案:

答案 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:没试过这个。