module Formol class Category < ActiveRecord::Base #Modules include RankedModel #Associations has_many :forums, :dependent => :destroy, :order => 'formol_forums.position' #Validations validates :label, :presence => true, :length => { :in => 3..32, :allow_blank => true }, :uniqueness => { :case_sensitive => false, :allow_blank => true } #Normalization normalize_attributes :label, :with => [:squish, :blank] #Sorting ranks :position #Scopes class << self # return categories conveniently ordered and eager-loaded for listing def ready_for_listing includes(:forums => { :last_post => [:user, :topic] }).rank(:position) end end #Business class << self # Sorts categories from an array of ids def sort(category_ids) #TODO: should maybe optimize this? (category_ids || []).each_with_index do |category_id, index| find(category_id).update_attribute(:position, index) end end end end end