Module: CapsuleCRM::Associations::BelongsTo::ClassMethods
- Defined in:
- lib/capsule_crm/associations/belongs_to.rb
Instance Method Summary collapse
-
#belongs_to(association_name, options = {}) ⇒ Object
Public: Add getter and setter methods for belongs to associations.
Instance Method Details
#belongs_to(association_name, options = {}) ⇒ Object
Public: Add getter and setter methods for belongs to associations
association_name - The String name of the association options - The Hash of additional options (default: {}):
class_name: The String name of the associated
class
Examples
class CapsuleCRM::Person
include CapsuleCRM::Associations::BelongsTo
belongs_to :organisation, class_name: 'CapsuleCRM::Organization'
end
organisation = CapsuleCRM::Organisation.find(1)
person = CapsuleCRM::Person.new(organisation = organisation) person.organisation_id
> 1
person.organisation
> organisation
34 35 36 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 |
# File 'lib/capsule_crm/associations/belongs_to.rb', line 34 def belongs_to(association_name, = {}) association = CapsuleCRM::Associations::BelongsToAssociation. new(association_name, self, ) self.associations[association_name] = association class_eval do attribute association.foreign_key, Integer end (class << self; self; end).instance_eval do define_method "_for_#{association_name}" do |id| CapsuleCRM::Associations::BelongsToFinder.new(association). call(id) end end define_method association_name do instance_variable_get(:"@#{association_name}") || if self.send(association.foreign_key) association.parent(self).tap do |object| self.send("#{association_name}=", object) end end end define_method "#{association_name}=" do |associated_object| associated_object.tap do |object| instance_variable_set(:"@#{association_name}", associated_object) self.send "#{association.foreign_key}=", associated_object.try(:id) end end end |