Class: ActiveRecord::Associations::BelongsToAssociation

Inherits:
Object
  • Object
show all
Defined in:
lib/hopsoft/acts_as_lookup.rb

Instance Method Summary collapse

Instance Method Details

#orig_replaceObject



243
# File 'lib/hopsoft/acts_as_lookup.rb', line 243

alias :orig_replace :replace

#replace(record) ⇒ Object

Overriding “replace” to allow implicit lookup table insertions. The assumption being that the only required field is the specified “key column” or in other words the column whose value we use to key off of.



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/hopsoft/acts_as_lookup.rb', line 248

def replace(record)
  if record.is_a?(Symbol) || record.is_a?(String)
    value = record.to_s
    attribute_name = proxy_reflection.table_name.singularize
    lookup_models = proxy_owner.class.lookup_models

    lookup_models.each do |model|
      if attribute_name =~ /^#{model.table_name.singularize}$/i
        record = model.get_record(value)

        if record.nil?
          new_record = model.new(model.key_column.to_sym => value)
          record = new_record if new_record.save
        end

        break
      end
    end

  end

  return orig_replace(record)
end