如何以嵌套哈希的形式从Rails DB中检索关系数据? [英] How to retrieve relational data from Rails DB in the form of a nested hash?

查看:77
本文介绍了如何以嵌套哈希的形式从Rails DB中检索关系数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails数据库中,有这些表:

In my Rails DB, I have these tables:


  • users

  • 状态(假设其名称包括 active 非活动),

  • status_records 每个用户在每个日期显示其状态(例如日期: 2019-07-09,用户:User.first,状态:Status.find_by(名称:活动)

  • users
  • statuses (let's say their names include active and inactive),
  • status_records for each date for each user to show their status (e.g. date: '2019-07-09', user: User.first, status: Status.find_by(name: 'active')

我想像这样在嵌套哈希中检索数据:

I would like to retrieve data in a nested hash like this:

data = {
  "active"=>{
    "Rick"=>["2019-07-09", "2019-07-10"],
    "Morty"=>["2019-07-09", "2019-07-10"],
    "Summer"=>["2019-07-09", "2019-07-10"]
  },
  "inactive"=>{
    "Rick"=>["2019-07-01", "2019-07-02", "2019-07-03"],
    "Summer"=>["2019-07-15"]
  }
}

到目前为止,我已经走了这么远。

So far, I've gotten this far.

data = StatusRecord.joins(:status, :user)
  .where(statuses: {name: ['active', 'inactive']})
  .select('status_records.date, statuses.name as status, users.name as username')
  .group_by(|record| [record.status, record.username])

上面的内容将我带到下面的数据结构中,但是如我先前所写,这并不是我想要的(我想将数据组织为嵌套的哈希)。

The above brings me to the data structure below, but as I wrote previously, this is not exactly what I want (I want to organise the data as a nested hash).

data = {
  ["active", "Rick"]=>["2019-07-09", "2019-07-10"],
  ["active", "Morty"]=>["2019-07-09", "2019-07-10"],
  ["active", "Summer"]=>["2019-07-09", "2019-07-10"],
  ["inactive", "Rick"]=> ["2019-07-01", "2019-07-02", "2019-07-03"],
  ["inactive", "Summer"]=>["2019-07-15"]
}

是否可以重写此查询,以便获取数据

Is there a way to rewrite this query so that I can get the data in the desired structure?

推荐答案

您快要准备好了!

您可以使用 Enumerable#each_with_object 来固定输出。

You can use Enumerable#each_with_object to fix your output a bit.

data = StatusRecord.joins(:status, :user)
  .where(statuses: {name: ['active', 'inactive']})
  .select('status_records.date, statuses.name as status, users.name as username')
  .each_with_object(Hash.new {|h,k| h[k] = Hash.new {|hh,kk| hh[kk] = [] } }) do |sr, hash|
    hash[sr.status][sr.username] << sr.date
  end

这篇关于如何以嵌套哈希的形式从Rails DB中检索关系数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆