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



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

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



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/active_repository/associations.rb', line 46

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



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/active_repository/associations.rb', line 65

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