Module: CapsuleCRM::Associations::HasMany::ClassMethods

Defined in:
lib/capsule_crm/associations/has_many.rb

Instance Method Summary collapse

Instance Method Details

#has_many(association_name, options = {}) ⇒ Object

Public: Add the setter and getter methods for a has_many association.

association_name - The String name of the associated collection options: - The Hash of options (default: {}):

:class_name - The String name of the class used in the
association
:source - the String method name used by the
object on the belongs_to side of the association
to set this object

Examples

class CapsuleCRM::Organizatio

include CapsuleCRM::Associations::HasMany

has_many :people, class_name: 'CapsuleCRM::Person', source: :person

end

organization = CapsuleCRM::Organization.find(1) organization.people

> [CapsuleCRM::Person, CapsuleCRM::Person, …]

person = CapsuleCRM::Organization.find(5) organization.people= [person] organization.people

> [person]



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/capsule_crm/associations/has_many.rb', line 37

def has_many(association_name, options = {})
  association = CapsuleCRM::Associations::HasManyAssociation.
    new(association_name, self, options)
  self.associations[association_name] = association

  if options[:embedded]
    define_method "save_#{association_name}" do
      unless self.send(association_name).blank?
        # TODO why can't I chain this?
        a = self.send(association_name)
        a.save
      end
    end

    class_eval do
      after_save :"save_#{association_name}" if respond_to?(:after_save)
      private :"save_#{association_name}"
    end

  end

  define_method association_name do
    instance_variable_get(:"@#{association_name}") ||
      instance_variable_set(:"@#{association_name}", association.proxy(self))
  end

  define_method "#{association_name}=" do |associated_objects|
    instance_variable_set :"@#{association_name}",
      association.proxy(self, associated_objects)
  end
end