Sha256: b42e955912c2709e8d75469c885607731cb6099d706493836b283c29fd8fa148

Contents?: true

Size: 821 Bytes

Versions: 35

Compression:

Stored size: 821 Bytes

Contents

# Adds a sort method to ActiveRecord class.  Given a list of IDs, it will sort
# the records in the order of the ids.  Assumes that the model has the :position attribute.
#
# ActiveRecord::Base.class_eval do
#    include RailsExtensions::ActiveRecord::Sort
# end

module CoreExtensions
  module ActiveRecord
    module Sort
      def self.included(base)
        base.extend ClassMethods

        base.before_create :set_position
      end

      module ClassMethods
        def sort(ids)
          ids.each_with_index do |id, index|
            where(id: id).update_all(["position=?", index + 1])
          end
        end
      end

      def set_position
        return unless respond_to?(:position)
        self.position = (self.class.where("position < 99999").maximum(:position) || 0) + 1
      end
    end
  end
end

Version data entries

35 entries across 35 versions & 1 rubygems

Version Path
renalware-core-2.0.16 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.15 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.14 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.13 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.12 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.11 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.9 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.8 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.7 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.5 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.4 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.3 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.2 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.1 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.0 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.0.pre.rc13 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.0.pre.rc11 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.0.pre.rc10 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.0.pre.rc9 lib/core_extensions/active_record/sort.rb
renalware-core-2.0.0.pre.rc8 lib/core_extensions/active_record/sort.rb