简体   繁体   English

Ruby on Rails对方法的结果进行排序

[英]Ruby on Rails sort on the result of a method

I have a helper method in a Rails site that checks how many attendees are in a certain class. 我在Rails站点中有一个帮助程序方法,该方法检查某个类中有多少与会者。 I have two different entities here, one for the class and one for attendee. 我在这里有两个不同的实体,一个用于班级,另一个用于参与者。 The helper method takes an activerecord result as an argument and calculates how many open slots there are based on the total spots minus the total people that have registered. helper方法将activerecord结果作为参数,并根据总点数减去已注册的总人数来计算有多少空位。 Is there any way that I can sort by the result of this so that courses with no open spots are put at the end of the list? 有什么办法可以对结果进行排序,以便将没有空缺的课程排在列表的末尾? Don't know if it will affect anything, but I am also using the will_paginate gem on the result set as well. 不知道它是否会影响任何事情,但是我也在结果集上使用了will_paginate gem。 I am currently ordering by the start date. 我目前正在开始日期之前订购。

Method in math_class.helper 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 Class View/Open Slots Column 数学类视图/开槽列

<% @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 %>

Controller Query statement 控制器查询语句

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

Consider using the block form of Array#sort : 考虑使用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

The spaceship operator <=> returns -1, 0 or 1 depending on if the left hand side is less than, equal to or greater than the right side. 航天器运算符<=>返回-1、0或1,具体取决于左侧是否小于,等于或大于右侧。 For example: 例如:

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

Array#sort uses this to order the elements in the array. Array#sort使用此命令对数组中的元素进行Array#sort

您将必须使用order_by Ruby方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM