Created
April 28, 2014 16:15
-
-
Save shamil614/11376683 to your computer and use it in GitHub Desktop.
Using Scopes on Arel Join Queries
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
# Let's say you have a join between Address and Job | |
# You want to use a scope on Job to limit the jobs that have to be joined otherwise you would join all jobs. | |
# So you try this | |
Address.joins('INNER JOIN jobs ON jobs.id = addresses.addressable_id AND addresses.addressable_type = "Job" AND ' \ | |
'addresses.address_type = "physical"').where(Job.in_the_future) | |
# What you get is an error like so | |
# Job Load (1.1ms) SELECT `jobs`.* FROM `jobs` WHERE (start_datetime > '2014-04-28 16:06:12') | |
# (pry) output error: #<TypeError: Cannot visit ActiveRecord::Relation::ActiveRecord_Relation_Job> | |
# You see the condition is correct in the SQL but the query is referencing Job | |
# What you need to be able to extract the conditions out of the scope | |
Address.joins | |
('INNER JOIN jobs ON jobs.id = addresses.addressable_id AND addresses.addressable_type = "Job" AND ' \ | |
'addresses.address_type = "physical"').where(Job.in_the_future.arel.where_clauses) | |
# Now you'll have a SQL query that runs properly and looks like this | |
"SELECT `addresses`.* FROM `addresses` INNER JOIN jobs ON jobs.id = addresses.addressable_id AND addresses.addressable_type = \"Job\" AND addresses.address_type = \"physical\" WHERE ((start_datetime > '2014-04-28 16:13:21'))" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment