Module: Volt::Associations::ClassMethods

Defined in:
lib/volt/models/associations.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(method_name, options = {}) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/volt/models/associations.rb', line 4

def belongs_to(method_name, options = {})
  collection  ||= options.fetch(:collection, method_name).pluralize
  foreign_key ||= options.fetch(:foreign_key, :id)
  local_key   ||= options.fetch(:local_key, "#{method_name}_id")

  # Add a field for the association_id
  field(local_key)

  # getter
  define_method(method_name) do
    association_with_root_model('belongs_to') do |root|
      # Lookup the associated model id
      lookup_key = get(local_key)

      # Return a promise for the belongs_to
      root.get(collection).where(foreign_key => lookup_key).first
    end
  end

  define_method(:"#{method_name}=") do |obj|
    id = obj.is_a?(Fixnum) ? obj : obj.id

    # Assign the current model's something_id to the object's id
    set(local_key, id)
  end
end

#has_many(method_name, options = {}) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/volt/models/associations.rb', line 31

def has_many(method_name, options = {})
  collection  ||= options.fetch(:collection, method_name).pluralize

  # Use the underscored current class name as the something_id.
  foreign_key ||= options.fetch(:foreign_key, "#{to_s.underscore.singularize}_id")
  local_key   ||= options.fetch(:local_key, :id)

  define_method(method_name) do
    lookup_key = get(local_key)
    array_model = root.get(collection).where(foreign_key => lookup_key)

    # Since we are coming off of the root collection, we need to setup
    # the right parent and path.
    new_path = array_model.options[:path]
    # Assign path and parent
    array_model.path = self.path + new_path
    array_model.parent = self

    array_model
  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.



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/volt/models/associations.rb', line 55

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