【问题标题】:Add attribute to ActiveRecord_Relation results based on existence of relationship?根据关系的存在向 ActiveRecord_Relation 结果添加属性?
【发布时间】:2016-11-01 06:02:29
【问题描述】:

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

不过,我尝试过的一切似乎都没有接近。

【问题讨论】:

    标签: mysql ruby-on-rails activerecord


    【解决方案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: 这个没试过。

    【讨论】:

      猜你喜欢
      • 2020-04-22
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多