2015-12-29 24 views
0

我在Rails站點中有一個幫助器方法,用於檢查某個類中有多少與會者。我在這裏有兩個不同的實體,一個用於課堂,另一個用於與會者。輔助方法將主動記錄結果作爲參數,並根據總點數減去已登記的總人數計算出有多少個空位。有沒有什麼方法可以根據這個結果進行排序,以便將沒有空位的課程放在列表的最後?不知道它是否會影響任何內容,但我也在結果集上使用了will_paginate gem。我目前在開始日期前訂購。Ruby on Rails根據方法的結果排序

在math_class.helper方法

def open_slots(math_class) 
    math_attendees = Attendee.where(:math_class_id => math_class.id).count 
    return math_class.total_spots - math_attendees 
end 

數學類檢視/開啓插槽列

<% @math_classes.each do |math_class| %> 
    <!-- Other columns... --> 
<% if open_slots(math_class) > 0 %> 
    <td> 
    <%= pluralize(open_slots(math_class), 'slot') %> of 
    <%= math_class.total_spots %> remaining 
    </td> 
<% else %> 
    <td><span class="text-error">No Open Slots</span></td> 
<% end %> 

控制器查詢語句

@math_classes = MathClass.joins(:room).order("starts_at").page(params[:page]).per_page(100) 

回答

0

你將不得不使用order_by Ruby方法。

1

考慮使用的Array#sort塊形式:

@math_classes = MathClass.joins(:room).order("starts_at").page(params[:page]).per_page(100) 
@math_classes.to_a.sort! do |a, b| 
    a_open_spots = a.total_spots - a.attendees.count 
    b_open_spots = b.total_spots - b.attendees.count 
    a_open_spots <=> b_open_spots 
end 

宇宙飛船操作者<=>返回-1,0或1取決於如果左側比右側小於,等於或更大。例如:

3 <=> 4 # => -1 
3 <=> 3 # => 0 
4 <=> 3 # => 1 

Array#sort使用該命令數組中的元素。

+0

看起來很方便,但total_spots是math_classes中的一列。當我嘗試這個total_spots未定義時出現錯誤。如果您嘗試to_a轉換不會刪除activerecord列名稱,並且不允許您引用total_spots? –

+0

實例變量'@ math_classes'應該與'MathClass :: ActiveRecord_Relation'類似。 'to_a'將這個關係轉換爲'MathClass'的實際實例。從那裏,我們應該能夠根據這個類的屬性進行排序。例如:'math_classes.to_a.sort {| a,b | a.total_spots <=> b.total_spots}' –