diff --git a/app/models/machine.rb b/app/models/machine.rb index cad417c2e7..c6f8a53cb1 100644 --- a/app/models/machine.rb +++ b/app/models/machine.rb @@ -441,7 +441,14 @@ class ResurrectionExpiredError < StandardError; end ) end } - scope :for_product, -> id { joins(:license).where license: { product_id: id } } + + # FIXME(ezekg) Remove this once we can assert product_id is fully denormalized. + if License.exists?(product_id: nil) + scope :for_product, -> id { joins(:product).where(product: { id: }) } + else + scope :for_product, -> id { joins(:license).where(license: { product_id: id }) } + end + scope :for_policy, -> id { joins(:license).where license: { policy_id: id } } scope :for_group, -> id { where(group: id) } diff --git a/app/models/user.rb b/app/models/user.rb index a5b5c3ac7d..fde1be889c 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -290,27 +290,13 @@ def owned = where(owner: proxy_association.owner) end } - scope :for_product, -> id { - license_users = LicenseUser.arel_table - licenses = License.arel_table - users = User.arel_table - - # More optimized union query for this particular association - left_outer_joins(:license_users) - .joins( - Arel::Nodes::InnerJoin.new( - licenses, - Arel::Nodes::On.new( - licenses[:user_id].eq(users[:id]).or( - licenses[:id].eq(license_users[:license_id]), - ) - ), - ), - ) - .where( - licenses: { product_id: id }, - ) - } + # FIXME(ezekg) Remove this once we can assert product_id is fully denormalized. + if License.exists?(product_id: nil) + scope :for_product, -> id { joins(:products).where(products: { id: }).distinct } + else + scope :for_product, -> id { joins(:licenses).where(licenses: { product_id: id }).distinct } + end + scope :for_license, -> id { joins(:licenses).where(licenses: { id: id }).distinct } scope :for_group_owner, -> id { joins(group: :owners).where(group: { group_owners: { user_id: id } }).distinct } scope :for_user, -> id {