2016-11-01 8 views
0

私はusersテーブル、notificationsテーブル、および結合テーブルnotification_readsを持っています。私はすべての通知(Notification.all)を返すActiveRecordクエリのスコープを作成しようとしています。そのフィールドには、その通知に対して相関するnotification_readがあるかどうかに基づいて追加のフィールドがあります。私が試した関係の存在に基づいてActiveRecord_Relationの結果に属性を追加しますか?

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

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:これを試していません。

関連する問題