Skip to content

Instantly share code, notes, and snippets.

@sporto
Created December 14, 2012 00:39
Show Gist options
  • Save sporto/4281464 to your computer and use it in GitHub Desktop.
Save sporto/4281464 to your computer and use it in GitHub Desktop.
How to access a subquery in an active record association object?
# we have a query like this one:
# but in some cases it will return duplicate records because of the joins
subquery = Workspace
.joins(:workspace_roles)
.where('workspace_roles.role_id IN (?)', role_ids)
.joins(:workspace_locations => :location)
.where('workspace_locations.location_id IN (?)', location_ids)
.where('locations.active = 1')
# on in order not to return duplicates we do the following:
subquery = Workspace
.select(:id)
.joins(:workspace_roles)
.where('workspace_roles.role_id IN (?)', role_ids)
.joins(:workspace_locations => :location)
.where('workspace_locations.location_id IN (?)', location_ids)
.where('locations.active = 1')
query = Workspace.where(id: subquery)
# A class returns this active record asssociation
# after this query has been created I want to attach conditions to the subquery
How can I get access to it?
query = query.some_way_to_access_subquery.where('locations.language_id IN (?), language_ids)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment