2017-01-12 96 views
0

當我試圖創建一個ActiveRecord查詢計數統計不同所有events其中position = move_left爲特定的用戶,加入到statusesstatus要麼movedmoved_correct。我遇到的問題是我的events可能有多個記錄,並且具有相同數據的特定用戶,因爲它們是事件,並且您可以多次執行相同的事件。ActiveRecord的連接表

我的兩個型號:

事件:

belongs_to :user 
belongs_to :status 

狀態:

belongs_to :user 
has_many :events 

由於有多個用戶,我需要爲每個特定用戶最後創建event,並加入到statuses其中statuses.positionmovedmoved_correct

SELECT `events`.* FROM `events` ORDER BY `events`.`id` DESC 

=> <Event id: 1, user_id: 1, position: "move_left"> 
=> <Event id: 2, user_id: 1, position: "right"> 
=> <Event id: 3, user_id: 1, position: "move_left"> 

=> <Event id: 4, user_id: 2, position: "move_left"> 
=> <Event id: 5, user_id: 2, position: "right"> 
=> <Event id: 6, user_id: 3, position: "right"> 

..

SELECT `statuses`.* FROM `statuses` ORDER BY `statuses`.`id` DESC 

=> <Status id: 1, status_now: "moved", user_id: 1> 
=> <Status id: 2, status_now: "moved_correct", user_id: 1> 

=> <Status id: 3, status_now: "moved", user_id: 2> 
=> <Status id: 4, status_now: "moved_correct", user_id: 3> 
=> <Status id: 5, status_now: "moved_down", user_id: 3> 

隨着樣本數據,我希望看到的總數將是4(user_id: 1返回2,user_id: 2返回1,user_id: 3 1返回)

這是我如何描繪它的一個示例查詢,但我不確定哪裏出錯。任何幫助將不勝感激!

Event.select(:user_id).distinct.order(id: :desc).first.joins("JOIN statuses ON events.user_id = statuses.user_id AND 
statuses.status_now IN ('moved', 'moved_correct')").count 

回答

0

根據我對你的特定情景的假設,試試這個:

Event.joins(:user).joins(:status) 
.where("statuses.status_now IN ('moved', 'moved_correct') AND events.position = 'move_left')" 
.distinct.count("events.id") 
+0

這似乎並沒有正常工作。爲了澄清我正在尋找更多的東西:SELECT DISTINCT COUNT(DISTINCT statuses.id)FROM'events' INNER JOIN'statuses' ON'statuses'.'user_id' ='activity_events'.'user_id' WHERE(statuses.status_now IN('moved','moved_correct')AND events.position ='move_left') - 但是基於最後一個唯一的'events.user_id'來計算'statuses'數量 –