通过协会订购

时间:2015-02-08 12:15:55

标签: ruby-on-rails ruby-on-rails-3.2

我试图通过相当复杂的关联来订购查询而没有运气。

以下是模型的相关部分......

class Athlete < ActiveRecord::Base
  has_many :participations
  has_many :matches, :through => :participations
  scope :active, -> { where(active: true) }
end

class Participation < ActiveRecord::Base
  belongs_to :athlete
  belongs_to :match
end

class Match < ActiveRecord::Base
  has_many :participations, :dependent => :destroy
  has_many :athletes, :through => :participations
  scope :unplayed,      -> { where("started_at is NULL and year=2015") }
end

我需要通过&#34; athlete.matches.unplayed.count&#34;订购一系列运动员。所以我有has_many:通过协会处理以及&#34; unplayed&#34;匹配范围。

在回复评论时添加清晰度。具体来说,我在视图中有这个表:

            <% @athletes.each do |athlete| %>
                <% match = athlete.matches.in_progress.first %>
                <tr>
                    <td><%= athlete.full_name %></td>
                    <td><%= athlete.idle? ? "Idle" : "Playing" %></td>

                    <% if athlete.idle? %>
                        <td></td>
                        <td></td>
                        <td></td>
                    <% else %>
                        <td><%= match.sport_name %></td>
                        <td><%= match.arena_name %></td>
                        <td><%= match.elapsed_time_string %></td>
                    <% end %>
                    <td><%= athlete.matches.unplayed.count %></td>
                </tr>
            <% end %>

我喜欢这张桌子,因此@athletes,按照我显示的最后一栏排序&#34; athletes.matches.unplayed.count&#34;。

来自控制器的@athletes是:

@athletes = Athlete.active

提前致谢!

1 个答案:

答案 0 :(得分:0)

我创建了这个范围

scope :order_by_machets_unplayed, ->
  {joins(:matches).where('matches.started_at is NULL and matches.year=2015').group('athletes.id').order("count(matches.id) desc")} 

不优雅,但有效

  • 赞成: 数据库对您的元素进行排序,非ruby
  • 缺点
    • 不干
    • 阅读起来并不简单