2011-04-06 9 views
0

에서 사용할 수있는 노래에 대해 카테고리 목록을 검색하는 가장 Rails-ish 방법을 찾고 있습니다. 여기SQL을 레일즈 3으로 변환 ActiveRecord

이 (! 순진 불구하고) 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; 

내 작업에 대한 SQL에 액티브

에 포트 여기에
## 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) 

을 시도 내가 마지막 하나려고하고 있지만 보인다 내가 SQL로 쓰는 것처럼?

더 많은 레일스가되도록 개선 할 방법이 있습니까?

답변

0

모델 설정을 게시하면 확실히 도움이 될 것입니다. 그러나 가정 :
이 * 노래 has_many : 범주 : => 범주화를 통해
*이 앨범은 거기에 노래의 거대한 양의가없는

왜 그냥하지 :

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