Module: ZTK::DSL::Core::Relations::BelongsTo::ClassMethods Private

Defined in:
lib/ztk/dsl/core/relations/belongs_to.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Author:

Instance Method Summary (collapse)

Instance Method Details

- (Object) belongs_to(key, options = {})

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/ztk/dsl/core/relations/belongs_to.rb', line 50

def belongs_to(key, options={})
  belongs_to_relations[key] = {
    :class_name => key.to_s.classify,
    :key => key
  }.merge(options)

  define_method(key) do |*args|
    if args.count == 0
      get_belongs_to_reference(key)
    else
      send("#{key}=", *args)
    end
  end

  define_method("#{key}=") do |value|
    set_belongs_to_reference(key, value)
  end

  define_method("#{key}_id") do |*args|
    if args.count == 0
      attributes["#{key}_id".to_sym]
    else
      send("#{key}_id=".to_sym, args.first)
    end
  end

  define_method("#{key}_id=") do |value|
    options = self.class.belongs_to_relations[key]
    if value != attributes["#{key}_id".to_sym]
      item = options[:class_name].constantize.find(value).first
      set_belongs_to_reference(key, item)
    else
      value
    end
  end

end