新手问题 后台数据返回处理

xiaoxiao · 2013年07月13日 · 最后由 jiek85 回复于 2013年07月13日 · 2710 次阅读

我在数据库中的数据是如下 我在控制器中的代码如下 @boy=Boy.where(:fileid=>a) 现在我需要返回给前台的数据应该如下 这怎么处理 Boy.where(:fileid=>a).where(:code=>'01010002').collect(&:name).join(',') 可以得到需要的 name Boy.where(:fileid=>a).where(:code=>'01010002').sum(:quantity) 可以得到需要的 quantity 但是这个@boy怎么写呢。。。

可以参考 Enumerable#group_by

Boy.where(fileid: a).group_by(:code).map do |_, boys|
  boys.inject do |hellboy, boy|
    hellboy.name << ',' << boy.name
    hellboy.quantity += boy.quantity
    hellboy
  end
end

如果想在 sql 做也可以,只要数据库是 oracle 或者 postgresql, 都能简单的 select code, string_agg(name, ',') as name, sum(quantity) as quantity, fileid from ... where ... group by code 就出来了,但是 mysql 的 group 语句太土鳖整不了。

mysql "select group_concat(name)", sum(quantity) from xx where xx group by code

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