Module: ContentfulModel::Associations::HasMany::ClassMethods
- Defined in:
- lib/contentful_model/associations/has_many.rb
Instance Method Summary collapse
-
#has_many(association_names, options = {}) ⇒ Object
has_many is called on the parent model.
Instance Method Details
#has_many(association_names, options = {}) ⇒ Object
has_many is called on the parent model
e.g class Foo
has_many :bars, class_name: "Something"
end The only reason for this method is that we might want to specify a relationship which is different from the name of the model we’re calling. If you specify a class_name, the method called on the parent will be that. e.g. .somethings in this example
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/contentful_model/associations/has_many.rb', line 19 def has_many(association_names, = {}) = { class_name: association_names.to_s.singularize.classify, inverse_of: self.to_s.underscore.to_s } = .merge() define_method association_names do begin # Start by calling the association name as a method on the superclass. # this will end up in ContentfulModel::Base#method_missing and return the value from Contentful. # We set the singular of the association name on each object in the collection to allow easy # reverse recursion without another API call (i.e. finding the Foo which called .bars()) super().collect do |child| child.send(:"#{[:inverse_of]}=",self) end rescue ContentfulModel::AttributeNotFoundError # If AttributeNotFoundError is raised, that means that the association name isn't available on the object. # We try to call the class name (pluralize) instead, or give up and return an empty collection if [:class_name].pluralize.underscore.to_sym != association_names self.send([:class_name].pluralize.underscore.to_sym) else #return an empty collection if the class name was the same as the association name and there's no attribute on the object. [] end end end end |