【问题标题】:How can I join only one record on a has_many with criteria in Rails?如何使用 Rails 中的条件在 has_many 上仅加入一条记录?
【发布时间】:2018-11-21 19:07:27
【问题描述】:

如果我有以下模型,我如何返回用户创建的所有报告,但只返回每个玩家的“最高评分”报告?

class Player < ApplicationRecord
  has_many :reports
end

class Report < ApplicationRecord
  belongs_to :author
  belongs_to :grade
  belongs_to :player
end

class Grade < ApplciationRecord
  has_many :reports
end

class Author < ApplicationRecord
  has_many :reports
end

示例数据:

/Player/    -    /Author/   -    /Report Grade/
John Smith        -    David      -        5
John Smith        -    David      -        4
Thomas Li         -    David      -        5
Mike Lee          -    Sean       -        9
Mike Lee          -    Sean       -        2
Arnold Jackson    -    Sean       -        5
Cathleen Miller   -    Sean       -        7

我想要的结果:

/Player/    -    /Author/   -    /Report Grade/
John Smith        -    David      -        5
Thomas Li         -    David      -        5
Mike Lee          -    Sean       -        9
Arnold Jackson    -    Sean       -        5
Cathleen Miller   -    Sean       -        7

目前我正在使用以下内容:

Report.joins(:player).where(type: %w(spring fall))

我不确定如何过滤掉“评分较低”的记录。如果我需要包含更多信息,请告诉我。

【问题讨论】:

  • 你真的需要为Grade 单独的表吗?如果你只是在reports 上使用一个整数会简单得多。
  • @max,是的,等级值比此处显示的更复杂。我只是为了说明而简化了它。

标签: ruby-on-rails activerecord ruby-on-rails-5


【解决方案1】:

在 Postgres 上,您可以使用 DISTINCT ON:

class Report < ApplicationRecord
  belongs_to :player
  belongs_to :grade
  belongs_to :author

  def self.highest_graded
    Report.select(%q{
      DISTINCT ON(reports.player_id, reports.author_id)
      grades.grade AS max_grade,
      players.name AS player_name,
      authors.name AS author_name,
      reports.*
    }).joins(:player, :grade, :author)
      .order('reports.player_id, reports.author_id, grades.grade DESC')
  end
end

<table>
  <thead>
    <tr>
      <th>id</th>
      <th>Player</th>
      <th>Author</th>
      <th>Grade</th>
    </tr>
  </thead>
  <tbody>
    <% Report.highest_grade.each do |report| %>
    <tr>
      <td><%= report.id %></td>
      <td><%= report.player_name %></td>
      <td><%= report.author_name %></td>
      <td><%= report.max_grade %></td>
    </tr>
    <% end %>
  </tbody>
</table>

id  Player          Author  Grade
1   John Smith      David   5
3   Thomas Li       David   5
4   Mike Lee        Sean    9
6   Arnold Jackson  Sean    5
7   Cathleen Miller Sean    7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    相关资源
    最近更新 更多