Module: ActiveHash::Associations::Methods

Defined in:
lib/associations/associations.rb

Instance Method Summary collapse

Instance Method Details

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



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/associations/associations.rb', line 134

def belongs_to(association_id, options = {})

  options = {
    :class_name => association_id.to_s.classify,
    :foreign_key => association_id.to_s.foreign_key,
    :primary_key => "id"
  }.merge(options)

  field options[:foreign_key].to_sym

  define_method(association_id) do
    options[:class_name].constantize.send("find_by_#{options[:primary_key]}", send(options[:foreign_key]))
  end

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

end

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



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

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,
      :primary_key => self.class.primary_key
    }.merge(options)

    klass = options[:class_name].constantize
    primary_key_value = send(options[:primary_key])
    foreign_key = options[:foreign_key].to_sym

    if Object.const_defined?(:ActiveRecord) && ActiveRecord.const_defined?(:Relation) && klass < ActiveRecord::Relation
      klass.where(foreign_key => primary_key_value)
    elsif klass.respond_to?(:scoped)
      klass.scoped(:conditions => {foreign_key => primary_key_value})
    else
      klass.where(foreign_key => primary_key_value)
    end
  end
end

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



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/associations/associations.rb', line 118

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