Module: Ymodel::Relatable
- Included in:
- Base
- Defined in:
- lib/ymodel/relatable.rb
Overview
This module contains YModel logic for managing relations.
Instance Method Summary collapse
-
#belongs_to(model, options = {}) ⇒ Object
This method is used to define the key on which relations are build.
-
#has_many(model, class_name: nil, as: nil, foreign_key: nil) ⇒ Object
rubocop:disable Naming/PredicateName rubocop:disable Naming/UncommunicativeMethodParamName.
- #has_one(model, class_name: nil, as: nil, foreign_key: nil) ⇒ Object
Instance Method Details
#belongs_to(model, options = {}) ⇒ Object
This method is used to define the key on which relations are build. We default to ‘id’.
12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/ymodel/relatable.rb', line 12 def belongs_to(model, = {}) define_method(model) do = Helper.model_class([:class_name] || model) key = if < Base :"#{model.to_s.singularize}_#{.index}" else :"#{.to_s.singularize}_id" end .find(self[key]) end end |
#has_many(model, class_name: nil, as: nil, foreign_key: nil) ⇒ Object
rubocop:disable Naming/PredicateName rubocop:disable Naming/UncommunicativeMethodParamName
28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/ymodel/relatable.rb', line 28 def has_many(model, class_name: nil, as: nil, foreign_key: nil) if as && foreign_key foreign_key ||= default_foreign_key define_method(model) do relation_class = Helper.model_class(class_name || model) if as relation_class.where("#{as}_id" => id, "#{as}_type" => self.class.name) else relation_class.where(foreign_key.to_sym => index) end end end |
#has_one(model, class_name: nil, as: nil, foreign_key: nil) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/ymodel/relatable.rb', line 43 def has_one(model, class_name: nil, as: nil, foreign_key: nil) if as && foreign_key foreign_key ||= default_foreign_key define_method(model) do relation_class = Helper.model_class(class_name || model) return relation_class.find_by(foreign_key => index) unless as relation_class.find_by("#{as}_id" => id, "#{as}_type" => self.class.name) end end |