所属栏目中的组函数 [英] Group function in belongs_to association rails
问题描述
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
描述关系,但在中使用表名
方法以指定列.这将生成这样的SQL请求:'qualifications'
group
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
- ActiveRecord的文档(搜索
joins
): http://guides.rubyonrails.org/active_record_querying.html - SQL
JOINS
的解释: http://www.w3schools.com/sql/sql_join.asp - Documentation of ActiveRecord (search for
joins
) : http://guides.rubyonrails.org/active_record_querying.html - Explanation of SQL
JOINS
: http://www.w3schools.com/sql/sql_join.asp
这篇关于所属栏目中的组函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!