为什么80%的码农都做不了架构师?>>>
相当于 acts_as_sortable, 很容易理解。
先来看看常用的方法
scope :rank, lambda { |name|order arel_table[ ranker(name.to_sym).column ]
}
def ranks *argsself.rankers ||= []ranker = RankedModel::Ranker.new(*args)self.rankers << rankerattr_accessor "#{ranker.name}_position"public "#{ranker.name}_position", "#{ranker.name}_position="end
其实就只要掌握这两个方法就行了!
看例子学习
class Duck < ActiveRecord::Baseinclude RankedModelranks :row_orderend
跟据上面所说的,你可以:
Duck.rank(:row_order).all
当更新时,您不必这么做:
@duck.update_attribute :row_order_position, 0
而是这么做:
$.ajax({type: 'PUT',url: '/ducks',dataType: 'json',data: { duck: { row_order_position: 0 } }, // or whatever your new
position is
});
要是觉得上面的太‘简单’,我们来点‘复杂’的
class Duck < ActiveRecord::Baseinclude RankedModelranks :row_order, # Name this ranker, used with rank():column => :sort_order # Override the default column, which
defaults to the namebelongs_to :pondranks :swimming_order,:with_same => :pond_id # Ducks belong_to Ponds, make the ranker
scoped to one pondscope :walking, where(:walking => true )ranks :walking_order,:scope => :walking # Narrow this ranker to a scopeend
现在你可以这么做
Duck.rank(:row_order)Pond.first.ducks.rank(:swimming_order)Duck.walking.rank(:walking)
一个方法指定要排序的属性(定义),一个方法为真正的(调用),就是两个普通的方法。