连接表时ActiveRecord计数不同

时间:2017-01-12 08:18:15

标签: mysql ruby-on-rails ruby activerecord

我正在尝试创建一个ActiveRecord查询,该查询计算特定用户events的所有position = move_left,当statusesstatus时加入moved {1}}或moved_correct。我正在努力解决的问题是我的events可能有多条记录,其中包含特定用户的相同数据,因为它们是事件,您可以多次执行同一事件。

我的两个模特:

事件:

belongs_to :user
belongs_to :status

状态:

belongs_to :user
has_many :events

由于有多个用户,我需要为每个特定用户获取上次创建的event,然后加入statuses statuses.positionmoved或{{1}的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

1 个答案:

答案 0 :(得分:0)

根据我对你给定场景的假设,试试这个:

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