代码之家  ›  专栏  ›  技术社区  ›  Darkerstar

Ruby on Rails ActiveRecord在一个SQL中查找平均值并将分页

  •  2
  • Darkerstar  · 技术社区  · 15 年前

    我有以下模范协会:一个学生模范并且有很多分数。

    我需要列出他们的名字和平均分,最低分,最高分。到目前为止我正在使用 学生。分数。每个学生的平均(:分数),我意识到它是在为每个学生做一个SQL。如何使用一个连接的SQL创建列表?

    另外,我如何将它与will-paginate插件一起使用?

    谢谢你

    1 回复  |  直到 15 年前
        1
  •  1
  •   Daniel Beardsley    15 年前

    你想要 :group :select 学生选项。查找。这应该对你有用:

    students = Student.all(
      :select => "
        students.*,
        AVG(scores.score) as avg_score,
        MIN(scores.score) as min_score,
        MAX(scores.score) as max_score",
      :joins => :scores
      :group => 'students.id')
    

    计算列与实际列一样可用,但显然不会保存它们。

    students.first.avg_score
    students.first.min_score
    students.first.max_score
    

    用于任意分页 ,只需包含您的:页面,:每页,…期权和看涨期权 Student.paginate 而不是 find . 如果发现分页的页数错误是因为 选项,只需添加: :total_entries => Student.count 你的论点