Module: Mongoid::Lists::ClassMethods

Defined in:
lib/mongoid/lists.rb

Instance Method Summary collapse

Instance Method Details

#lists(name, options = {}) ⇒ Mongoid:Relations:Metadata

Macro to set relation on which to make a list

Parameters:

  • relation (Symbol)

    The name of the has_many relation

  • options (Hash) (defaults to: {})

    The options hash

Returns:

  • (Mongoid:Relations:Metadata)

    Instance of metadata for the relation

Since:

  • 0.0.1



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/mongoid/lists.rb', line 19

def lists name, options={}
  meta       = reflect_on_association name
  field_name = options[:column] || 
    (meta.foreign_key.to_s.gsub(/_?id$/, '_position')).to_sym
  

  # Override the default ids setter, first setting the correct position
  # on each relation based on the index of its id in the given array.
  #
  # @override model#{name}_ids= 
  before_method self, "#{name.to_s.singularize}_ids=" do |ids|
    ids.each_with_index do |id, index|
      meta.klass.find(id).update_attribute field_name, index + 1
    end
  end

  meta[:order] ||= "#{field_name} asc"
end