从另一个表中采集时计算不同的记录

时间:2017-11-11 01:32:15

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord

鉴于Rails应用程序位于:

class Team < ActiveRecord::Base
  belongs_to :captain, class_name: User

我正在尝试简洁地查询数据库并获取Captains的摘要以及他们所属的团队数量:

[[23, "Pat", "Smith"]]  Teams: 1
[[46, "Kate", "Jones"]]  Teams: 1
[[107, "John", "Doe"]]  Teams: 3
...

我可以获得每个船长的ID和团队数量的哈希值:

> Team.group(:captain_id).count
=> {85=>3, 106=>1, 81=>1, 25=>1, 32=>1, 8=>3, 1=>1, 79=>2, 26=>1}

然而它变得丑陋。以下工作,但看起来很丑,并有n + 1个SQL查询:

Team.group(:captain_id).count.sort.to_h.each { |key,val| puts "#{User.where(id: key).pluck(:id, :first, :last)}  Teams: #{val}" }

Rails的方式是什么?

2 个答案:

答案 0 :(得分:1)

由于您正在尝试获取有关用户的详细信息,因此您可能希望在用户模型上定义这样的关系:

class User < ActiveRecord::Base
  has_many :captained_teams, foreign_key: :captain_id, class_name: Team

然后,您可以使用用户查询:

User.joins(:captained_teams).includes(:captained_teams).each do |user|
  puts "#{[user.id, user.first, user.last]}  Teams: #{user.captained_teams.length}"
end

答案 1 :(得分:0)

sql = "**Select count then group by then having count(...)**"

result = ActiveRecord :: Base.connection.execute(sql);

您可以使用原始sql来获得您想要的内容。