Module: ActiveHash::Associations::Methods

Defined in:
lib/associations/associations.rb

Instance Method Summary collapse

Instance Method Details

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



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/associations/associations.rb', line 27

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
    options[:class_name].constantize.find_by_id(send(options[:foreign_key]))
  end

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

end

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



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/associations/associations.rb', line 9

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

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