Created
December 14, 2012 00:39
-
-
Save sporto/4281464 to your computer and use it in GitHub Desktop.
How to access a subquery in an active record association object?
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
# 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