Module: CompositePrimaryKeys::ActiveRecord::Overides

Defined in:
lib/composite_primary_keys/active_record_overides.rb

Instance Method Summary collapse

Instance Method Details

#create_record(attribute_names = nil) ⇒ Object

This override ensures that pkeys are set on the instance when records are created. However, while ActiveRecord::Persistence defines a create_record method the call in create_or_update is actually calling the method create_record in the Dirty concern which removes the pkey attrs and also sets updated/created at timestamps For some reason when we overide here we lose dirty! So, for now, timestamps are recorded explicitly



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/composite_primary_keys/active_record_overides.rb', line 11

def create_record(attribute_names = nil)
  run_callbacks(:create) do
    record_timestamps!
    attribute_names ||= keys_for_partial_write
    attributes_values = arel_attributes_with_values_for_create(attribute_names)

    new_id = self.class.unscoped.insert attributes_values

    # DB like MySQL doesn't return the newly inserted result.
    # self.id cannot be updated for this case.
    self.id = new_id if self.class.primary_key and new_id.kind_of?(Array)
    
    @new_record = false
    id
  end
end

#record_timestamps!Object



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/composite_primary_keys/active_record_overides.rb', line 28

def record_timestamps!
  if self.record_timestamps
    current_time = current_time_from_proper_timezone

    all_timestamp_attributes.each do |column|
      if respond_to?(column) && respond_to?("#{column}=") && self.send(column).nil?
        write_attribute(column.to_s, current_time)
      end
    end
  end
end