Skip to content

Instantly share code, notes, and snippets.

@shamil614
Created April 28, 2014 16:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shamil614/11376683 to your computer and use it in GitHub Desktop.
Save shamil614/11376683 to your computer and use it in GitHub Desktop.
Using Scopes on Arel Join Queries
# 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