Module: Gecko::Helpers::AssociationHelper
- Included in:
- Record::Base
- Defined in:
- lib/gecko/helpers/association_helper.rb
Overview
Helper for has_many/belongs_to relationships
Instance Method Summary collapse
-
#belongs_to(model_name, options = {}) ⇒ undefined
Set up a belongs_to relationship between two classes based on a JSON key of class_name_id.
-
#has_many(association_name, options = {}) ⇒ undefined
Set up a has_many relationship between two classes based on a JSON key of class_name_ids.
Instance Method Details
#belongs_to(model_name, options = {}) ⇒ undefined
Set up a belongs_to relationship between two classes based on a JSON key of class_name_id.
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/gecko/helpers/association_helper.rb', line 22 def belongs_to(model_name, ={}) class_name = [:class_name] || model_name.to_s.classify foreign_key = model_name.to_s.foreign_key.to_sym define_method model_name do if (id = attributes[foreign_key]) @client.adapter_for(class_name).find(id) end end attribute foreign_key, Integer, readonly: [:readonly] end |
#has_many(association_name, options = {}) ⇒ undefined
Set up a has_many relationship between two classes based on a JSON key of class_name_ids.
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/gecko/helpers/association_helper.rb', line 51 def has_many(association_name, ={}) model_name = association_name.to_s.singularize class_name = [:class_name] || model_name.classify foreign_key = model_name.foreign_key.pluralize.to_sym readonly = .key?(:readonly) ? [:readonly] : true define_method association_name do ids = self.attributes[foreign_key] if ids.any? @client.adapter_for(class_name).find_many(ids) else [] end end attribute foreign_key, Array[Integer], readonly: readonly end |