Module: SugarCRM::AssociationMethods

Defined in:
lib/sugarcrm/associations/association_methods.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#associate!(target, opts = {}) ⇒ Object Also known as: relate!

Creates a relationship between the current object and the target object The current and target records will have a relationship set i.e. account.associate!(contact) would link account and contact In contrast to using account.contacts << contact, this method doesn’t load the relationships before setting the new relationship. This method is useful when certain modules have many links to other modules: not loading the relationships allows one to avoid a Timeout::Error



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/sugarcrm/associations/association_methods.rb', line 28

def associate!(target,opts={})
  targets = Array.wrap(target)
  targets.each do |t|
    association = @associations.find!(t)
    response = self.class.session.connection.set_relationship(
      self.class._module.name, self.id, 
      association.link_field, [t.id], opts
    )
    if response["failed"] > 0
      raise AssociationFailed, 
      "Couldn't associate #{self.class._module.name}: #{self.id} -> #{t}: #{t.id}!" 
    end
    # We need to update the association cache for any changes we make.
    if opts[:delete] == 1
      update_association_cache_for(association.link_field, t, :delete)
      t.update_association_cache_for(association.link_field, self, :delete)
    else
      update_association_cache_for(association.link_field, t, :add)
      t.update_association_cache_for(t.associations.find!(self).link_field, self, :add)
    end
  end
  true
end

#disassociate!(target) ⇒ Object Also known as: unrelate!

Removes a relationship between the current object and the target object



54
55
56
# File 'lib/sugarcrm/associations/association_methods.rb', line 54

def disassociate!(target)
  associate!(target,{:delete => 1})
end

Returns the module link fields hash



17
18
19
# File 'lib/sugarcrm/associations/association_methods.rb', line 17

def link_fields
  self.class._module.link_fields
end

#save_modified_associations!Object

Saves all modified associations.



7
8
9
10
11
12
13
14
# File 'lib/sugarcrm/associations/association_methods.rb', line 7

def save_modified_associations!
  @association_cache.values.each do |collection|
    if collection.changed?
      collection.save!
    end
  end
  true
end