Rails 有办法把 SQL 子查询用 scope 方法来实现嘛

luffycn · 2015年02月09日 · 最后由 luffycn 回复于 2015年02月10日 · 2356 次阅读

Articles 表 select * from articles where id in (select Max(id) from table group by name) and category_id in ('a', 'b')

有办法把这样的 sql 结果,在 Article model 中,通过 scope 的方式实现嘛?

有,lambda

class Group
  scope maxids: -> {  Group.group(:name).maximum(:id).values }
end

Article.where(id: Group.maxids).where(category_id: ['a', 'b'])

这样怎么样?

@zlx_star nice, thanks. I will try

需要 登录 后方可回复, 如果你还没有账号请 注册新账号