所属栏目中的组函数 [英] Group function in belongs_to association rails

查看:67
本文介绍了所属栏目中的组函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

user.rb

enum gender: [:Male, :Female] 
belongs_to :qualification

qualification.rb

qualification.rb

has_many :users

查询时

User.all.group(:gender).count.map { |k, v| [User.genders.key(k), v] }.to_h

它给了我

{"Male"=>18, "Female"=>1}

但是我不知道要为资格做同样的事情,因为它涉及到关联.我该怎么做?

But I doesn't know to do same for qualification because association is involve in it.How I do it?

User.all.group(:qualification_id).count.map { ??? }

推荐答案

您可以通过使用关联名称为 joins()的关联模型在关联模型之间执行联接,然后按任意分组联接模型的列.

You can perform a join between your associated models by using joins() with the name of the association, and then group by any column of the joined model.

例如,如果您要按 name 资格列进行分组:

For example, if you want to group by the name column of qualification :

User.joins(:qualification).group('qualifications.name').count

joins 方法中使用符号:qualification 描述关系,但在中使用表名'qualifications'group 方法以指定列.这将生成这样的SQL请求:

Use the symbol :qualification describing the relation in the joins method, but use the table name 'qualifications' in the group method in order to specify the column. This will generate a SQL request like this :

SELECT COUNT(users.id)
FROM users
INNER JOIN qualifications ON users.qualification_id = qualifications.id
GROUP BY qualifications.name

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