2014-04-05 45 views
0

我試圖查詢每個板子的人的點擊次數。 所以我可以顯示該董事會成員的表格。併爲每個顯示他得到的點擊次數。ActiveRecord與兩個有很多集合和一個group_by查詢

如何爲此信息創建activeRecord查詢?

我的3種型號:

class Click < ActiveRecord::Base 
    belongs_to :board 
    belongs_to :person 
end 

class Board < ActiveRecord::Base 
    has_many :persons, dependent: :destroy 
    has_many :clicks, dependent: :destroy 
end 

class Person < ActiveRecord::Base 
    belongs_to :board 
    has_many :clicks, dependent: :destroy 
end 
+0

可能重複:http://stackoverflow.com/questions/7690463/getting-a-nested-object-collection-trough-active-record – wurde

+0

抱歉,但我不認爲他們是一樣的..我的關係很好。我只是試圖用activeRecord構建一個無關緊要的查詢 –

回答

1

嗯,有很多方法來建立你的這個查詢,其中之一是:

Click.where(person_id: your_person_id_variable, board_id: your_board_id_variable) 

這樣你與點擊的數組人員和董事會信息。你也有數組大小,代表點擊次數。

您也可以使用board作爲主要模型,並使用sql joins帶來其他數據。它基本上是相同的方法:

Board.joins([:persons, :clicks]).where("persons.id = #{your_person_id_variable} 
    AND clicks.id = #{your_board_id_variable}") 

你應該在這種關係的一部分和ActiveRecord的查詢界面看看Rails的指南。還要廣泛使用Rails控制檯,您可以測試任何內容並輕鬆理解所有概念。

+0

我給它一個鏡頭!謝謝 –

+0

嗨,你能告訴我請...有一種方法,我可以得到他們所有?..我不想要一個特定的人。我想要顯示董事會下所有用戶的表格。不是特定的人。 –