Module: DbReference::ClassMethods

Defined in:
lib/db_reference/active_record_ext.rb

Instance Method Summary collapse

Instance Method Details

#update_or_create(attributes = {}) ⇒ Object

Given a hash of attributes including the ID, look up the record by ID.

If it does not exist, it is created with the rest of the options. If it exists, it is updated with the given options.

Returns the record.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/db_reference/active_record_ext.rb', line 13

def update_or_create(attributes = {})
  id = attributes.delete(:id)
  
  record = find_or_initialize_by_id(id)
  
  attributes.each_pair do |key, value|
    record.send "#{key}=", value
  end
  
  begin
    record.save!
  rescue
    puts "Save failed for #{record.class}[#{id}] with attributes #{attributes.inspect}"
    raise
  end

  record
end