查找表中的最大整数?

时间:2014-04-17 16:45:50

标签: ruby-on-rails

挑战:

我需要在论坛中找到最受欢迎的讨论。

背景资料:

  • 论坛有很多讨论
  • 讨论属于论坛
  • 讨论有一个名为views的属性,可存储多少个属性 用户查看讨论的次数。
  • 使用postgres数据库。

我的解决方案:

Forum模型中创建一个实例方法,循环每一个讨论,并查看每个讨论的视图数量:

def most_popular_discussion 
    record_view = 0

    self.discussions.each do |d|
        record_views = d.views if d.views > record_views 
    end

    record_views
end

为什么我提出了一个问题:

我的解决方案似乎是灾难性的低效率,因为它在查询表中查询每个条目。随着数据库变得越来越大,这种方法会越来越慢。我不介意太多,但most_popular_discourse方法也会被要求很多(在每个用户的个人资料页面上),并且会让事情变得缓慢。

那么如何找到表中最大的整数? 或(我认为这可能是更好的方式)我是否应该实际保存记录的观看次数,而不是每次都进行处理?

我的应用程序可能还有另一个名为statistics的表,只有两列,name:stringinformation:string并使用它存储其他统计信息?

然后,每当有人观看讨论时,我都会像这样

def iterate_views(ip)
    current_views = self.views + 1 

    self.views = current_views        

    record_views_statistic = Statistic.find_by(name: 'record_views')
    record_views_statistic.update_attributes(information: current_views.to_s) if current_views > record_views_statistic.information 

    # I convert current_views to a string before saving because the statistics table's `information` column holds strings in order to keep the table open and miscellaneous. 
end

您如何看待这种方法?两者都与数据库进行了相当的交互,但第二种方法不会与数据库中的数据量成比例地减慢。

1 个答案:

答案 0 :(得分:1)

这种方法将为您提供最受欢迎的讨论,并且比您的两种解决方案简单得多。

def most_popular_discussion
  self.discussions.order(views: :desc).first
end

要获得最多的观看次数,您可以使用most_popular_discussion.views或使用以下功能:

def record_views
  self.discussions.maximum(:views)
end

请注意,我已经找到了查找观看次数最多的观看次数和观看次数最多的方法,因为您的挑战表明您希望找到最受欢迎的讨论,但两种解决方案似乎都找到了记录编号论坛讨论中的观点。

至于您的解决方案,您的第二个解决方案似乎更接近于一个好的解决方案,但为什么不在views模型中缓存最受欢迎的讨论Forum计数?假设我们在record_views表中添加了forums列。

class Discussion < ActiveRecord::Base
  belongs_to :forum

  def iterate_views
    self.views += 1
    if self.forum.present? && self.views > self.forum.record_views
      self.forum.record_views = self.views 
    end
  end
end

然后,找到Forum模型中最受欢迎的讨论(假设关系无关紧要):

def most_popular_discussion
  self.discussions.where(views: self.record_views).first
end
相关问题