0
當我試圖創建一個ActiveRecord查詢計數統計不同所有events
其中position = move_left
爲特定的用戶,加入到statuses
當status
要麼moved
或moved_correct
。我遇到的問題是我的events
可能有多個記錄,並且具有相同數據的特定用戶,因爲它們是事件,並且您可以多次執行相同的事件。ActiveRecord的連接表
我的兩個型號:
事件:
belongs_to :user
belongs_to :status
狀態:
belongs_to :user
has_many :events
由於有多個用戶,我需要爲每個特定用戶最後創建event
,並加入到statuses
其中statuses.position
是moved
或moved_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
這似乎並沒有正常工作。爲了澄清我正在尋找更多的東西: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'數量 –