首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将SQL转换为Rails 3 ActiveRecord

将SQL转换为Rails 3 ActiveRecord
EN

Stack Overflow用户
提问于 2011-04-06 14:13:16
回答 1查看 416关注 0票数 0

我正在寻找一种最简单的Rails方式来检索给定专辑上可用歌曲的分类列表。

这里是SQL album_id =1

代码语言:javascript
复制
-- 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

代码语言:javascript
复制
## 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?

EN

回答 1

Stack Overflow用户

发布于 2011-04-06 18:27:41

好吧,如果你把你的模型设置好了肯定会有帮助的。但假设:

*歌曲has_many :类别,通过=>分类

*一张专辑中没有大量的歌曲

为什么不直接做:

代码语言:javascript
复制
Album.includes({:songs => {:categorizations => :categories}}).find(1).songs.collect {|s| s.category}.flatten.uniq
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5567779

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档