2015-02-08 110 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