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

luffycn · February 09, 2015 · Last by luffycn replied at February 10, 2015 · 2357 hits

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

You need to Sign in before reply, if you don't have an account, please Sign up first.