相当于 acts_as_sortable, 很容易理解。
scope :rank, lambda { |name|
order arel_table[ ranker(name.to_sym).column ]
}
def ranks *args
self.rankers ||= []
ranker = RankedModel::Ranker.new(*args)
self.rankers << ranker
attr_accessor "#{ranker.name}_position"
public "#{ranker.name}_position", "#{ranker.name}_position="
end
其实就只要掌握这两个方法就行了!
class Duck < ActiveRecord::Base
include RankedModel
ranks :row_order
end
跟据上面所说的,你可以:
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::Base
include RankedModel
ranks :row_order, # Name this ranker, used with rank()
:column => :sort_order # Override the default column, which
defaults to the name
belongs_to :pond
ranks :swimming_order,
:with_same => :pond_id # Ducks belong_to Ponds, make the ranker
scoped to one pond
scope :walking, where(:walking => true )
ranks :walking_order,
:scope => :walking # Narrow this ranker to a scope
end
现在你可以这么做
Duck.rank(:row_order)
Pond.first.ducks.rank(:swimming_order)
Duck.walking.rank(:walking)
一个方法指定要排序的属性(定义),一个方法为真正的(调用),就是两个普通的方法。