Module: Volt::Associations::ClassMethods
- Defined in:
- lib/volt/models/associations.rb
Instance Method Summary collapse
- #belongs_to(method_name, key_name = nil) ⇒ Object
- #has_many(method_name, remote_key_name = nil) ⇒ Object
-
#has_one(method_name) ⇒ Object
has_one creates a method on the Volt::Model that returns a promise to get the associated model.
Instance Method Details
#belongs_to(method_name, key_name = nil) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/volt/models/associations.rb', line 4 def belongs_to(method_name, key_name = nil) key_name ||= "#{method_name}_id" # Add a field for the association_id field(key_name) # getter define_method(method_name) do association_with_root_model('belongs_to') do |root| # Lookup the associated model id lookup_key = get(key_name) # Return a promise for the belongs_to root.get(method_name.pluralize).where(id: lookup_key).first end end end |
#has_many(method_name, remote_key_name = nil) ⇒ Object
21 22 23 24 25 |
# File 'lib/volt/models/associations.rb', line 21 def has_many(method_name, remote_key_name = nil) define_method(method_name) do get(method_name.pluralize, true) end end |
#has_one(method_name) ⇒ Object
has_one creates a method on the Volt::Model that returns a promise to get the associated model.
29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/volt/models/associations.rb', line 29 def has_one(method_name) if method_name.plural? raise NameError, "has_one takes a singluar association name" end define_method(method_name) do association_with_root_model('has_one') do |root| key = self.class.to_s.underscore + '_id' root.send(method_name.pluralize).where(key => id).first end end end |