Skip to content

Instantly share code, notes, and snippets.

@hopsoft

hopsoft/assignable_job.rb

Last active May 15, 2018
Embed
What would you like to do?
Arel subquery condition
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
class Assignment < ApplicationRecord
belongs_to :record, polymorphic: true
end
@danshultz

This comment has been minimized.

Copy link

@danshultz danshultz commented May 15, 2018

What is this model? Is it a polymorphic relationship?

Rails should handle this...

class Foo < ActiveRecord::Base
  has_many :assignments, polymorphic: true
  
  scope :assigned, -> { assignments.any? }
end
@danshultz

This comment has been minimized.

Copy link

@danshultz danshultz commented May 15, 2018

...wait, you are looking for any that are assigned...let me retry that...

class Foo < ActiveRecord::Base
  has_many :assignments, polymorphic: true
  # this _should_ work
  scope :assigned, -> { joins(:assignments) }
  # but this is similar and includes a `where assignments.id is not null` with the join.
  scope :assigned, -> { joins(:assignments).merge(Assignments.where.not(id: nil)) }
end
@hopsoft

This comment has been minimized.

Copy link
Owner Author

@hopsoft hopsoft commented May 15, 2018

Thanks for the feedback. Experimenting now... but it appears to be returning duplicate AssignableJob records.

@hopsoft

This comment has been minimized.

Copy link
Owner Author

@hopsoft hopsoft commented May 15, 2018

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
You can’t perform that action at this time.