2015-12-29 25 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}' –