Class: NaranyaEcm::Rest::Associations::HasMany
- Inherits:
-
Association
- Object
- Association
- NaranyaEcm::Rest::Associations::HasMany
- Defined in:
- lib/naranya_ecm/rest/associations.rb
Instance Attribute Summary
Attributes inherited from Association
#associated_class, #klass, #name, #options
Instance Method Summary collapse
- #foreign_key ⇒ Object
-
#initialize(klass, name, options = {}) ⇒ HasMany
constructor
A new instance of HasMany.
- #macro ⇒ Object
Methods inherited from Association
Constructor Details
#initialize(klass, name, options = {}) ⇒ HasMany
Returns a new instance of HasMany.
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 |
# File 'lib/naranya_ecm/rest/associations.rb', line 40 def initialize(klass, name, = {}) super # Define the Getter: klass.send :define_method, name do value = self.instance_variable_get "@#{name}".to_sym if value.nil? reflection = self.class.reflect_on_association name foreign_key = (self.class.name.demodulize.underscore + '_id').to_sym value = self.instance_variable_set( "@#{name}".to_sym, # reflection.associated_class.where(foreign_key => self.id) AssociationRelation.new(reflection.associated_class, reflection.foreign_key, self.id) ) end value end # Define the setter klass.send :define_method, "#{name}=".to_sym do |new_value| reflection = self.class.reflect_on_association(name) relation = AssociationRelation.new(reflection.associated_class, reflection.foreign_key, self.id) relation.load new_value unless new_value.nil? instance_variable_set "@#{name}".to_sym, relation end end |
Instance Method Details
#foreign_key ⇒ Object
37 38 39 |
# File 'lib/naranya_ecm/rest/associations.rb', line 37 def foreign_key @foreign_key ||= @options[:foreign_key] || @options.has_key?(:inverse_of) ? "#{@options[:inverse_of]}_id".to_sym : "#{@klass.name.demodulize.underscore}_id".to_sym end |
#macro ⇒ Object
67 |
# File 'lib/naranya_ecm/rest/associations.rb', line 67 def macro; :has_many; end |