Module: Gecko::Helpers::AssociationHelper::ClassMethods
- Defined in:
- lib/gecko/helpers/association_helper.rb
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.
29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/gecko/helpers/association_helper.rb', line 29 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.
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/gecko/helpers/association_helper.rb', line 60 def has_many(association_name, = {}) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength 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 # rubocop:disable Metrics/MethodLength collection_proxies[association_name] ||= begin ids = attributes[foreign_key] collection = if ids.any? @client.adapter_for(class_name).find_many(ids) else [] end build_collection_proxy(collection, **{ embedded: [:embedded], class_name: class_name, association_name: association_name }) end end attribute foreign_key, Array[Integer], readonly: readonly end |