2015-02-08 107 views
0

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

下面是该机型的相关部分...

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 

我需要通过“athlete.matches.unplayed.count”订购运动员的集合。所以我有has_many:通过关联来处理以及Match上的“未播放”范围。

在回应评论时增加清晰度。具体地讲,我有这样的表中的图:

  <% @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,由最后一列我显示“athletes.matches.unplayed.count”排序。

从控制器,@athletes是:提前

@athletes = Athlete.active 

谢谢!

+0

'由什么order'?期望的结果是什么? – 2015-02-08 12:19:15

+0

我需要通过“athlete.matches.unplayed.count”在栏杆中返回的内容来命令返回的一组运动员。 – 2015-02-08 12:22:52

+0

还不清楚...... – 2015-02-08 12:25:28

回答

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")} 

是不优雅,但工程

  • 优点: 数据库排序你的元素,不红宝石
  • 缺点
    • 不是干的
    • 它不是简单的阅读
+0

这是运动员模型的范围? – 2015-02-08 14:26:14

+0

我知道,不是DRY:/。 但我告诉你,这是一个部分的解决方案。您需要在运动员中创建一个新字段以存储该计数。之后,如果比赛发生变化,你可以更新你的计数 – 2015-02-08 14:55:39