Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 查找表中的最大整数?_Ruby On Rails - Fatal编程技术网

Ruby on rails 查找表中的最大整数?

Ruby on rails 查找表中的最大整数?,ruby-on-rails,Ruby On Rails,挑战: 我需要在论坛中找到最受欢迎的讨论 背景信息: 论坛有很多讨论 讨论属于论坛 讨论有一个名为views的属性,它存储了多少个视图 用户查看讨论的次数 使用postgres数据库 我的解决方案: 在论坛模型中创建一个实例方法,在每个讨论中循环,查看每个讨论有多少视图: def most_popular_discussion record_view = 0 self.discussions.each do |d| record_views = d.vie

挑战:

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

背景信息:

  • 论坛有很多讨论
  • 讨论属于论坛
  • 讨论有一个名为
    views
    的属性,它存储了多少个视图 用户查看讨论的次数
  • 使用postgres数据库
我的解决方案:

论坛
模型中创建一个实例方法,在每个讨论中循环,查看每个讨论有多少视图:

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
我为什么提出一个问题:

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

那么我应该如何找到表中最大的整数呢或者(我认为这可能是更好的方法)我应该保存记录的浏览量,而不是每次都计算出来吗

可能有另一个名为
statistics
的表供我的应用程序使用,只有两列,
name:string
information: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

你认为这种方法怎么样?这两种方法都会与数据库进行相当程度的交互,但第二种方法不会随着数据库中的数据量成比例地降低速度。

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

def most_popular_discussion
  self.discussions.order(views: :desc).first
end
要获得最大数量的视图,您可以使用
most\u popular\u discussion.views
或使用以下功能:

def record_views
  self.discussions.maximum(:views)
end
请注意,我已经介绍了找到浏览量最大的讨论和最高浏览量的方法,因为您的挑战表明您希望找到最受欢迎的讨论,但您的两种解决方案似乎都能在论坛的讨论中找到创纪录的浏览量

至于您的解决方案,您的第二个解决方案似乎更接近于一个好的解决方案,但为什么不在
论坛
模型中缓存最受欢迎的讨论的
视图
计数?假设我们在
论坛
表中添加一个
记录视图

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

您应该在SQLDo中这样做。。讨论。最大值(“记录视图”)。。这将为您提供记录视图列中的最大值
def most_popular_discussion
  self.discussions.where(views: self.record_views).first
end