简体   繁体   English

定制红宝石在轨道上

[英]Custom ordering in ruby on rails

I have a teachers model, which displays teachers list in view, but I want that head of the school will be always top in the view, their helpers next and teachers last. 我有一个教师模型,该模型在视图中显示教师列表,但是我希望学校的负责人始终在视图中,其助手在其后,教师在后。

How I could add a custom sorting trough a form? 如何添加自定义排序槽? Maybe there is any javascript plugin which could move or down teachers in the list? 也许有任何JavaScript插件可以在列表中上移或下移教师?

In general, you can define an ordering between instances of a Ruby class by doing the following two steps: 通常,您可以通过执行以下两个步骤来定义Ruby类实例之间的顺序:

  1. include Comparable in the class definition. 在类定义中include Comparable
  2. Define a method <=> that takes a single parameter, which is another instance of the class. 定义一个采用单个参数的方法<=> ,这是该类的另一个实例。 This method should return 1 if the receiver ( self ) should be considered greater than the other object, -1 if it should be considered lesser, and 0 if they are equal. 如果应该认为接收方( self )大于另一个对象,则此方法应该返回1;如果应该认为较小(-1),则返回-1;如果它们相等,则返回0。

This isn't ActiveRecord-specific but I see no reason why it shouldn't work for an ActiveRecord class. 这不是特定于ActiveRecord的,但是我看不出为什么它不适用于ActiveRecord类。

Easiest way is to create a "group" attribute. 最简单的方法是创建“组”属性。 So: 所以:

your head of school with be group => 1 你的校长与小组=> 1
your helpers would be group => 2 您的助手将是组=> 2
your teachers would be group => 3 您的老师会成组=> 3

Then, something like Employee.order(:group).order(:last_name) would order by your groups and then order by last_name. 然后,类似Employee.order(:group).order(:last_name)将按您的组排序,然后按last_name排序。

to have a custom order, add that as your secondary sort. 要获得自定义订单,请将其添加为您的次级排序。

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

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