Class: NaranyaEcm::Rest::Associations::BelongsTo
- Inherits:
-
SingularAssociation
- Object
- Association
- SingularAssociation
- NaranyaEcm::Rest::Associations::BelongsTo
- 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 = {}) ⇒ BelongsTo
constructor
A new instance of BelongsTo.
- #macro ⇒ Object
Methods inherited from Association
Constructor Details
#initialize(klass, name, options = {}) ⇒ BelongsTo
Returns a new instance of BelongsTo.
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
# File 'lib/naranya_ecm/rest/associations.rb', line 91 def initialize(klass, name, = {}) super # Define the foreign key: klass.send :field, foreign_key, foreign_key: true # Define the setter klass.send :define_method, "#{name}=".to_sym do |new_value| reflection = self.class.reflect_on_association(name) foreign_key_name = reflection.foreign_key new_value = reflection.associated_class.new new_value if new_value.is_a? Hash raise "Type Mismatch on #{self.class.name} ##{name}= #{new_value.inspect}" unless new_value.nil? || new_value.class == reflection.associated_class self.send "#{foreign_key_name}=".to_sym, new_value.nil? ? nil : new_value.id instance_variable_set "@#{name}".to_sym, new_value end end |
Instance Method Details
#foreign_key ⇒ Object
110 111 112 |
# File 'lib/naranya_ecm/rest/associations.rb', line 110 def foreign_key @foreign_key ||= [:foreign_key] || "#{name}_id".to_sym end |
#macro ⇒ Object
109 |
# File 'lib/naranya_ecm/rest/associations.rb', line 109 def macro; :belongs_to; end |