You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I often use association subqueries over joins, because I get to reuse more scopes, and also because they don't require me to remember to add .distinct to avoid duplicate records if I'm joining a has_many association.
Artist.joins(:albums).where(albums: { ... }).distinct# have to remember the `DISTINCT`Artist.where(albums: Album.where(...))# don't need to add `DISTINCT`
One source of friction I'm encountering regularly is that, unlike joins, association subqueries don't handle :through associations. When I attempt to use them, I get an SQL error, which I already realize is because I used a :through assocation.
# association join cascades tablesArtist.joins(:tracks).where(tracks: {released: true})# SELECT * FROM artists# INNER JOIN albums ...# INNER JOIN tracks ...# association subquery doesn't handle table cascadingArtist.where(tracks: Track.released)# SELECT * FROM artists WHERE tracks.id IN (# SELECT tracks.id FROM tracks WHERE tracks.released IS TRUE# ) -- invalid query, no albums
This requires me to explicitly go through the intermediate associations, which can get cumbersome for longer chains.
Artist.where(albums: Album.where(tracks: Track.released))# SELECT * FROM artists WHERE artists.id IN (# SELECT albums.artist_id FROM albums WHERE albums.id IN (# SELECT tracks.album_id FROM tracks WHERE tracks.released IS TRUE# )# )
It would be really convenient if Active Record was able to automatically join intermediary associations (like the above):
Artist.where(tracks: Track.released)
Did anyone else have this use case? Would it make sense for Active Record to potentially support this functionality?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I often use association subqueries over joins, because I get to reuse more scopes, and also because they don't require me to remember to add
.distinct
to avoid duplicate records if I'm joining ahas_many
association.One source of friction I'm encountering regularly is that, unlike joins, association subqueries don't handle
:through
associations. When I attempt to use them, I get an SQL error, which I already realize is because I used a:through
assocation.This requires me to explicitly go through the intermediate associations, which can get cumbersome for longer chains.
It would be really convenient if Active Record was able to automatically join intermediary associations (like the above):
Did anyone else have this use case? Would it make sense for Active Record to potentially support this functionality?
Beta Was this translation helpful? Give feedback.
All reactions