Skip to content

Instantly share code, notes, and snippets.

@tuwukee
Created March 9, 2020 19:51
Show Gist options
  • Save tuwukee/78cc922ad59af0b0a78b12b470508069 to your computer and use it in GitHub Desktop.
Save tuwukee/78cc922ad59af0b0a78b12b470508069 to your computer and use it in GitHub Desktop.
Query example
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