2017-11-11 192 views
0

鑑於Rails應用程序,其中:計數不重複的記錄,同時從另一個表拔毛

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

我想簡潔查詢數據庫並獲得船長的總結和團隊的人數它們屬於:

[[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的方法是什麼?

+0

您的問題不是直接重複,但您可能會在[此問題及其答案]中找到有用的內容(https://stackoverflow.com/questions/17252669/rails-query-with-select-group-and -having-不會工作)。此外,使您的協會雙向。 – anothermh

回答

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 
+0

我不認爲你需要'.joins'和'.includes'。我認爲只有'.includes'才能完成這項工作。 – moveson

+1

'.joins'對於僅考慮隊長的用戶是必要的。 – cschroed

+0

這就是鐵軌的方式!通過「ActiveRecord」控制表上的查詢,儘可能簡化查詢。 –

0

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

結果= ActiveRecord的:: Base.connection.execute(SQL);

你可以使用原始的sql來得到你想要的。

相關問題