Created
March 9, 2020 19:51
-
-
Save tuwukee/78cc922ad59af0b0a78b12b470508069 to your computer and use it in GitHub Desktop.
Query example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Users | |
class AnnouncementsQuery | |
attr_accessor :used | |
def initialize(user) | |
@user = user | |
end | |
def unread | |
active | |
.joins(with_reads) | |
.where(announcement_reads: { id: nil }) | |
end | |
def read_later | |
active | |
.joins(with_reads(:inner)) | |
.where(announcement_reads: { read_later: true }) | |
end | |
private | |
def active | |
Announcement | |
.active | |
.order(:started_at) | |
end | |
def with_reads(join_type = :left) | |
case join_type | |
when :left then read_join 'LEFT OUTER' | |
when :inner then read_join 'INNER' | |
end | |
end | |
def read_join(type) | |
<<~SQLJOIN | |
#{type} JOIN | |
announcement_reads | |
ON | |
announcement_reads.announcement_id = announcements.id | |
AND | |
announcement_reads.user_id = #{@user.id} | |
SQLJOIN | |
.squish | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment