Module: Mongoid::ActsAsList::List::ClassMethods

Defined in:
lib/mongoid/acts_as_list/list.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_list(options = {}) ⇒ Object

Public: class macro to enable the ActsAsList module

options - a Hash of options

:field - the name of the field to hold the position number as a Symbol or a String (optional)
:scope - the name of the association to scope the list for (required for non-embedded models)

Examples

## on a belong_to relation

class List
  include Mongoid::Document

  has_many :items
end

class Item
  include Mongoid::Document
  include Mongoid::ActsAsList

  belongs_to :list
  acts_as_list scope: :list, field: :position
end

## on a embedded_in relation

class List
  include Mongoid::Document

  embeds_many :items
end

class Item
  include Mongoid::Document
  include Mongoid::ActsAsList

  embedded_in :list
  acts_as_list field: :num
end


52
53
54
55
56
57
58
59
# File 'lib/mongoid/acts_as_list/list.rb', line 52

def acts_as_list options = {}
  field = options.fetch(:field, Mongoid::ActsAsList.configuration.default_position_field).try(:to_sym)
  scope = options.fetch(:scope, nil).try(:to_sym)

  include list_submodule
  define_position_field field
  define_position_scope scope
end

#order_by_position(conditions = {}, order = :asc) ⇒ Object



61
62
63
64
# File 'lib/mongoid/acts_as_list/list.rb', line 61

def order_by_position(conditions = {}, order = :asc)
  order, conditions = [conditions || :asc, {}] unless conditions.is_a? Hash
  where( conditions ).order_by [[position_field, order], [:created_at, order]]
end