繁体   English   中英

Tricky Rails ActiveRecord(SQL是可以接受的!)查询在两个连接表中查找给定条件的用户比例

[英]Tricky Rails ActiveRecord (SQL is acceptable!) query to find a proportion of users given conditions in two join tables

class User < ActiveRecord::Base
  has_many :views
  has_many :rates
  ...
end

class Resource < ActiveRecord::Base
  has_many :views
  has_many :rates
  ...
end

我正在研究用户花在资源上的时间是否表明他们对资源的看法(我相信它是)。 这是一些更相关的数据:

在此输入图像描述

现在,我需要得到一个比例。 用户赞助资源GIVEN的比例是:

1)在资源上向上或向下投票

2)已查看资源至少5分钟

我怎样才能做到这一点?

(将继续尝试/挣扎于答案时更新此帖子)

让我们看看,也许我至少可以得到一个SQL查询,然后我们可以担心ActiveRecord-izing它:

SELECT resources.*, sum(case views.vote when 'up' 1 else 0 end) as up_votes, count(views.id) as total_views     
  FROM resources 
  JOIN views ON views.resource_id = resources.id
  JOIN rates ON rates.resource_id = resources.id 
    AND rates.user_id = views.user_id
  WHERE views.updated_at - views.created_at >= interval '5 minutes'
  AND views.vote IS NOT NULL
  GROUP BY resources.id

现在,我当然不完全确定这是对的,但它可能是一个开始。 然后,您可以将其分解为ActiveRecord形式,从而:

@resources = Resources.
  select("resources.*, sum(case views.vote when 'up' 1 else 0 end) as up_votes, count(views.id) as total_views").
  joins("JOIN views ON views.resource_id = resources.id JOIN rates ON rates.resource_id = resources.id AND rates.user_id = views.user_id").
  where("views.updated_at - views.created_at >= interval '5 minutes' AND views.vote IS NOT NULL").
  group("GROUP BY resources.id")

up_votestotal_views将附加到每个Resource对象,因此您可以调用和操作它们(我发现它们由于某种原因被转换为字符串,因此您可能需要在.to_f上使用.to_f

ratios = @resources.map{|r| r.up_votes.to_f/r.total_views.to_f}

如果您希望数据库按比率或某些比例排序,您也可以在select进行除法。

如果您实际上只想要所有资源的比率,只需取出分组(虽然我不知道ActiveRecord会涉及到那里,除非它提供与数据库的连接)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM