Module: ActiveHash::Associations::Methods

Defined in:
lib/associations/associations.rb

Instance Method Summary collapse

Instance Method Details

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



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/associations/associations.rb', line 94

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



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

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 ActiveRecord.const_defined?(:Relation) && klass.all.class < ActiveRecord::Relation
      klass.where(options[:foreign_key] => id)
    elsif klass.respond_to?(:scoped)
      klass.scoped(:conditions => {options[:foreign_key] => id})
    else
      klass.send("find_all_by_#{options[:foreign_key]}", id)
    end
  end
end

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



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/associations/associations.rb', line 78

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