2011-04-06 3 views
0

Je recherche le moyen le plus Rails-ish pour récupérer une liste distincte de catégories pour les chansons disponibles sur un album donné.Conversion de SQL en Rails 3 ActiveRecord

Ici, il est dans SQL pour album_id = 1

-- Using subselects 
select * from categories where id in (
    select distinct category_id 
    from categorizations 
    where song_id in (select song_id from album_songs 
        where album_id = 1 and available = 't') 
) 
order by name asc; 

-- Using joins 
select distinct c.* from categories c 
    inner join categorizations cz on c.id = cz.category_id 
    left join album_songs a on cz.song_id = a.song_id 
where a.album_id = 1 and a.available = 't' 
order by c.name asc; 

Mon travail (quoique naïf!) Tente de porter ce à ActiveRecord

## attempting to do it like subselects (although they're not really 
## subselects, it executes them individually -- from what i've read 
## ActiveRecord won't do subselects?) 
Category.where('id IN (?)', 
    Categorization.select('DISTINCT category_id').where('song_id IN (?)', 
    Album.find(1).songs.available.map(&:song_id) 
).map(&:category_id) 
).order('name ASC') 

## joins - although at this point it's pretty much all sql 
## as i couldn't find a way to do the left join in pure AR 
## i'm also duplicating my AlbumSongs.available scope -- is 
## that scope reusable here? (outside the AlbumSongs model?) 
Category.select('DISTINCT categories.*') 
     .joins(:categorizations, 
       'LEFT OUTER JOIN album_songs ON categorizations.song_id = album_songs.song_id') 
     .where('album_songs.album_id = ? and available', 1) 

Je vais avec le dernier, mais il semble comme je pourrais aussi bien l'écrire en SQL?

Y a-t-il un moyen d'améliorer cela pour être plus Rails-ish?

Répondre

0

Eh bien, il serait certainement utile si vous postez votre configuration de modèle. Mais en supposant que:
* chanson has_many: catégories,: à travers => catégorisations
* un album n'a pas une énorme quantité de chansons sur elle

Pourquoi ne pas le faire:

Album.includes({:songs => {:categorizations => :categories}}).find(1).songs.collect {|s| s.category}.flatten.uniq