lib/sugarcrm/associations/association_methods.rb in sugarcrm-0.9.6 vs lib/sugarcrm/associations/association_methods.rb in sugarcrm-0.9.7
- old
+ new
@@ -18,10 +18,34 @@
return true if collection.changed?
end
false
end
+ # Creates a relationship between the current object and the target
+ # The current instance and target records will have a relationship set
+ # i.e. account.associate!(contact) wyould 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 ot avoid a Timeout::Error
+ def associate!(target, target_ids=[], opts={})
+ if self.class._module.custom_module? || target.class._module.custom_module?
+ link_field = get_link_field(target)
+ else
+ link_field = target.class._module.table_name
+ end
+ target_ids = [target.id] if target_ids.size < 1
+ response = SugarCRM.connection.set_relationship(
+ self.class._module.name, self.id,
+ link_field, target_ids,
+ opts
+ )
+ raise AssociationFailed,
+ "Couldn't associate #{self.class._module.name}: #{self.id} -> #{target.class._module.table_name}:#{target.id}!" if response["failed"] > 0
+ true
+ end
+
protected
def save_modified_associations
@association_cache.values.each do |collection|
if collection.changed?
@@ -67,8 +91,18 @@
# up some elegant way to handle this.
collection = AssociationCollection.new(self,association,true)
# add it to the cache
@association_cache[association] = collection
collection
+ end
+
+ # return the link field involving a relationship with a custom module
+ def get_link_field(other)
+ this_table_name = self.class._module.custom_module? ? self.class._module.name : self.class._module.table_name
+ that_table_name = other.class._module.custom_module? ? other.class._module.name : other.class._module.table_name
+ # the link field will contain the name of both modules
+ link_field = self.associations.detect{|a| a == [this_table_name, that_table_name].join('_') || a == [that_table_name, this_table_name].join('_')}
+ raise "Unable to determine link field between #{self.class._module.name}: #{self.id} and #{other.class._module.table_name}:#{other.id}" unless link_field
+ link_field
end
end; end
\ No newline at end of file