Module: ActiveHash::Associations::Methods

Defined in:
lib/associations/associations.rb

Instance Method Summary collapse

Instance Method Details

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



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/associations/associations.rb', line 167

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].safe_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



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/associations/associations.rb', line 124

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].safe_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

  define_method("#{association_id.to_s.underscore.singularize}_ids") do
    public_send(association_id).map(&:id)
  end
end

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



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/associations/associations.rb', line 150

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

    scope = options[:class_name].safe_constantize

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