Module: ActiveRecord::Persistence

Defined in:
lib/monkey_patch_activerecord.rb

Overview

Patches for Persistence to allow certain partitioning (that related to the primary key) to work.

Instance Method Summary collapse

Instance Method Details

#createObject

patch the create method to prefetch the primary key if needed



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/monkey_patch_activerecord.rb', line 59

def create
  if self.id.nil? && self.class.respond_to?(:prefetch_primary_key?) && self.class.prefetch_primary_key?
    self.id = connection.next_sequence_value(self.class.sequence_name)
  end

  attributes_values = arel_attributes_values(!id.nil?)

  new_id = self.class.unscoped.insert attributes_values

  self.id ||= new_id

  IdentityMap.add(self) if IdentityMap.enabled?
  @new_record = false
  id
end

#destroyObject

Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can’t be persisted).



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/monkey_patch_activerecord.rb', line 19

def destroy
  destroy_associations
  
  if persisted?
    IdentityMap.remove(self) if IdentityMap.enabled?
    pk         = self.class.primary_key
    column     = self.class.columns_hash[pk]
    substitute = connection.substitute_at(column, 0)
    
    if self.class.respond_to?(:dynamic_arel_table)
      using_arel_table = dynamic_arel_table()
      relation = ActiveRecord::Relation.new(self.class, using_arel_table).
        where(using_arel_table[pk].eq(substitute))
    else
      using_arel_table = self.class.arel_table
      relation = self.class.unscoped.where(using_arel_table[pk].eq(substitute))
    end
    
    relation.bind_values = [[column, id]]
    relation.delete_all
  end
  
  @destroyed = true
  freeze
end

#update(attribute_names = @attributes.keys) ⇒ Object

Updates the associated record with values matching those of the instance attributes. Returns the number of affected rows.



47
48
49
50
51
52
53
54
# File 'lib/monkey_patch_activerecord.rb', line 47

def update(attribute_names = @attributes.keys)
  attributes_with_values = arel_attributes_values(false, false, attribute_names)
  return 0 if attributes_with_values.empty?
  klass = self.class
  using_arel_table = self.respond_to?(:dynamic_arel_table) ? dynamic_arel_table() : klass.arel_table
  stmt = klass.unscoped.where(using_arel_table[klass.primary_key].eq(id)).arel.compile_update(attributes_with_values)
  klass.connection.update stmt
end