Module: ActiveRepository::Associations::Methods

Defined in:
lib/active_repository/associations.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

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

Defines “belongs to” type relation between ActiveRepository objects



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/active_repository/associations.rb', line 79

def belongs_to(association_id, options = {})
  options = {
    class_name:  association_id.to_s.classify,
    foreign_key: association_id.to_s.foreign_key
  }.merge(options)

  field options[:foreign_key].to_sym

  define_method(association_id) do
    klass = options[:class_name].constantize
    id    = send(options[:foreign_key])

    if id.present?
      object = klass.find_by_id(id)
    else
      nil
    end
  end

  define_method("#{association_id}=") do |new_value|
    attributes.delete(association_id.to_sym)
    send("#{options[:foreign_key]}=", (new_value.try(:id) ? new_value.id : new_value))
  end
end

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

Defines “has many” type relation between ActiveRepository objects



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/active_repository/associations.rb', line 42

def has_many(association_id, options = {})
  define_method(association_id) do
    options = {
      class_name:  association_id.to_s.classify,
      foreign_key: self.class.to_s.foreign_key
    }.merge(options)

    klass = options[:class_name].constantize
    objects = []

    if klass.respond_to?(:scoped)
      objects = klass.scoped(:conditions => {options[:foreign_key] => id})
    else
      objects = klass.send("find_all_by_#{options[:foreign_key]}", id)
    end
  end
end

#has_one(association_id, options = {}) ⇒ Object

Defines “has one” type relation between ActiveRepository objects



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/active_repository/associations.rb', line 61

def has_one(association_id, options = {})
  define_method(association_id) do
    options = {
      class_name:  association_id.to_s.classify,
      foreign_key: self.class.to_s.foreign_key
    }.merge(options)

    scope = options[:class_name].constantize

    if scope.respond_to?(:scoped) && options[:conditions]
      scope = scope.scoped(:conditions => options[:conditions])
    end
    
    scope.send("find_by_#{options[:foreign_key]}", id)
  end
end