Last active
May 15, 2018 14:08
-
-
Save hopsoft/a52aabf7bd1d3dde6eba61886d1ad922 to your computer and use it in GitHub Desktop.
Arel subquery condition
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
class AssignableJob < ApplicationRecord | |
has_many :assignments, as: :record, dependent: :destroy | |
scope :assigned, -> do | |
subquery = Assignment.where(record_type: name).where(Assignment.arel_table[:record_id].eq(arel_table[:id])).select(Assignment.arel_table[Arel.star].count) | |
where "(#{subquery.to_sql}) > 0" # TODO: move to Arel & remove string interpolation | |
end | |
end |
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
class Assignment < ApplicationRecord | |
belongs_to :record, polymorphic: true | |
end |
Adding distinct
produces what I'm after, but I worry about performance as the table grows.
class AssignableJob < ApplicationRecord
scope :assigned, -> { joins :assignments }
end
AssignableJob.assigned # returns duplicate records
AssignableJob.assigned.distinct # works
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the feedback. Experimenting now... but it appears to be returning duplicate
AssignableJob
records.