返回具有关联计数的模型

时间:2015-05-18 20:20:40

标签: ruby-on-rails ruby postgresql activerecord

我要回来的是什么

我的查询会返回一个哈希值,其中包含该人的身份证以及他们所播放的电视节目集数:

Person.joins(:contributions)
.where('contributions.role_id = 2')
.where('contributions.episode_id IN (?)', self.episodes.pluck(:id)).limit(5)
.group(:person_id).order('count_all desc').count

返回:

{26=>66, 14=>13, 17=>10, 30=>9, 9=>8}

(身份证号码为26的人已经上映过66集)

我想要归来的

如果我在.group之后取出所有内容,我会在数组中获得实际人物模型,但是(对于courrse)它们是未分类的并且没有计数。

[#<Person id: 26, first_name: "Natasha">, #<Person id: 1, first_name: "Steve"]

有没有办法获取此人的记录和计数? 例如:

[[ <Person id: 26, first_name: "Natasha">, 66 ], [<Person id: 1, first_name: "Steve", 13]]

1 个答案:

答案 0 :(得分:0)

我认为这有效:

 img {
    max-width: 100%;
    max-height: 100%;
    margin: auto;
    display:block;
    top: 0; left: 0; bottom: 0; right: 0;
    overflow:hidden;
}

这将在模型上添加一个字段Person.joins(:contributions) .where('contributions.role_id = 2') .where('contributions.episode_id IN (?)', self.episodes.select(:id)) .limit(5) .group(:person_id) .select('people.*, COUNT(*) AS count_all') .order('count_all desc') ,这可能比您想要的输出更好。如果您需要特定输出,可以添加:

count_all

到上面的查询结尾。

有一点需要注意:您可以在.map { |r| [r, r.count_all] } 部分使用select而不是pluck来阻止第二次查询。

修改

以上似乎在一些有限的测试中工作正常,即使生成的SQL有点错误(我们选择非聚合的非分组字段)。

您还可以将初始查询的值分配给episodes,然后:

hsh

只需一个额外的查询即可获得您喜欢的输出。