我正在寻找一种最简单的Rails方式来检索给定专辑上可用歌曲的分类列表。
这里是SQL 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;我的工作(虽然很天真!)尝试将其移植到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)我将使用最后一个,但似乎我还是用SQL编写它吧?
是否有任何方法来改善这一点,使之更多的是Rails?
发布于 2011-04-06 18:27:41
好吧,如果你把你的模型设置好了肯定会有帮助的。但假设:
*歌曲has_many :类别,通过=>分类
*一张专辑中没有大量的歌曲
为什么不直接做:
Album.includes({:songs => {:categorizations => :categories}}).find(1).songs.collect {|s| s.category}.flatten.uniqhttps://stackoverflow.com/questions/5567779
复制相似问题