Ruby on rails Rails-根据帖子、评论的数量列出最活跃的配置文件

Ruby on rails Rails-根据帖子、评论的数量列出最活跃的配置文件,ruby-on-rails,rails-postgresql,Ruby On Rails,Rails Postgresql,配置文件可以创建帖子。 个人资料可以评论帖子。 权重:post=1,comment=1 我需要在上个月内根据帖子、评论的综合权重列出人员 我尝试的是: profiles = Profile.find(:all, :include => [:posts, :comments], :conditions => ["posts.created_at > ? or comments.created_at > ?", 1.month.ago, 1.month.ago], :grou

配置文件可以创建帖子。 个人资料可以评论帖子。 权重:post=1,comment=1

我需要在上个月内根据帖子、评论的综合权重列出人员

我尝试的是:

profiles = Profile.find(:all, :include => [:posts, :comments], :conditions => ["posts.created_at > ? or comments.created_at > ?", 1.month.ago, 1.month.ago], :group => "profiles.id", :group => 'profiles.id, posts.id, comments.id', :limit => 5)


我建议我们根据在日期创建的对两个表进行左连接,并将每个表的非NULL值的总数作为一个名为总权重的新字段独立计算:

profiles = Profile.joins("LEFT JOIN posts ON posts.profile_id = profiles.id AND posts.created_at > ? LEFT JOIN comments ON comments.profile_id = profiles.id AND comments.created_at > ?", 1.month_ago, 1.month_ago).group("profiles.id").select("profiles.*, sum(posts.id IS NOT NULL) + sum(comments.id IS NOT NULL) as total_weight")
您可以在
顺序中使用
“total\u weight”
having
子句,并可以在结果中引用它:
配置文件。首先,total\u weight


<>我会考虑在“代码>配置文件< /代码>中使用一个新列中的相应计数或总数来使这个查询更快、更容易维护。您可以有一个每天运行的任务来更新每个配置文件上的记录,这样,必须获取记录的控制器就不必每次都启动此计算。

创建一个模型
Activities
,其中包含列
month、'comments\u count'、'posts\u count'、'profile\u id'

在您的
profile.rb
中,您有

has_many :activities
belongs_to :profile
activity.rb
,您有

has_many :activities
belongs_to :profile
在每个月末使用,运行一个作业,计算这些数字并为每个用户添加值

优点:

  • 您可以每月统计所有配置文件活动
  • 这将缓存输出并大大简化查询。您只需执行以下操作:
    profile.activities.where(月份:Date.today.month-1.month)
  • PS:您可以改进查询

    缺点: 1.随着时间的推移和剖面图的增加,很难进行维护


    如果您只想保留上个月的计数,这个问题将很容易解决。

    您的配置文件表中可以有两个属性::comments\u count&:posts\u count,并且每次用户写帖子或评论时,您都可以使用rails回调来增加这些值。在这种情况下,我们无法读取帖子或评论的时间。我需要最后一个月的顶级贡献者列表。在这种情况下,额外的字段将无助于我们考虑POST /评论的时间。那么,建议加入连接如何?如果您有一个脱机任务,比如每天一次,就可以更新额外字段。我们在应用程序中的一些地方这样做;e、 例如,如果一个对象处于一组其他状态且在2周内未更新,则将状态列更新为“隐藏”。这样,在主登录页上运行的查询就不必比较日期(速度非常慢),而只需与离线更新的索引状态列进行比较。