Module: Mongoid::Lookup::Model

Extended by:
ActiveSupport::Concern
Defined in:
lib/mongoid_lookup/model.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#has_lookup_changes?(name) ⇒ Boolean

checks for dirty fields on the given lookup

Parameters:

  • name (Symbol)

    name of lookup to check

Returns:

  • (Boolean)


30
31
32
33
34
# File 'lib/mongoid_lookup/model.rb', line 30

def has_lookup_changes? name
  lookup_fields = self.class.lookup_fields(name)
  changed_fields = changes.keys
  (changed_fields - lookup_fields).count < changed_fields.count
end

#lookup_reference_attributes(name) ⇒ Hash

the attributes required for the given lookup reference

Parameters:

  • name (Symbol)

    name of lookup to check

Returns:

  • (Hash)


40
41
42
43
44
45
46
47
# File 'lib/mongoid_lookup/model.rb', line 40

def lookup_reference_attributes name
  {}.tap do |attrs|
    map = self.class.lookup(name).lookup_field_map.invert
    map.keys.each do |source_field|
      attrs[map[source_field]] = read_attribute(source_field)
    end
  end
end

#maintain_lookup_reference(name) ⇒ Object

create or update the lookup reference if changes are present

Parameters:

  • name (Symbol)

    name of lookup reference to update



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/mongoid_lookup/model.rb', line 14

def maintain_lookup_reference name
  if has_lookup_changes?(name)
    attrs = lookup_reference_attributes(name)
    
    if ref = send("#{name}_reference")
      ref.update_attributes(attrs)
    else
      send("create_#{name}_reference", attrs)
    end
  end
end