Module: CompositePrimaryKeys::ActiveRecord::Persistence

Included in:
ActiveRecord::Base
Defined in:
lib/composite_primary_keys/persistence.rb

Instance Method Summary collapse

Instance Method Details

#relation_for_destroyObject



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/composite_primary_keys/persistence.rb', line 4

def relation_for_destroy
  return super unless composite?
  
  where_hash = {}
  primary_keys = Array(self.class.primary_key)

  if primary_keys.empty?
    raise ActiveRecord::CompositeKeyError, "No primary key(s) defined for #{self.class.name}"
  end

  primary_keys.each do |key|
    where_hash[key.to_s] = self[key]
  end

  relation = self.class.unscoped.where(where_hash)
end

#touch(name = nil) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/composite_primary_keys/persistence.rb', line 22

def touch(name = nil)
  attributes = timestamp_attributes_for_update_in_model
  attributes << name if name

  unless attributes.empty?
    current_time = current_time_from_proper_timezone
    changes = {}

    attributes.each do |column|
      column = column.to_s
      changes[column] = write_attribute(column, current_time)
    end

    changes[self.class.locking_column] = increment_lock if locking_enabled?

    @changed_attributes.except!(*changes.keys)

    relation    = self.class.send(:relation)
    arel_table  = self.class.arel_table
    primary_key = self.class.primary_key

    primary_key_predicate = relation.cpk_id_predicate(arel_table, Array(primary_key), Array(id))

    self.class.unscoped.where(primary_key_predicate).update_all(changes) == 1
  end
end

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



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/composite_primary_keys/persistence.rb', line 49

def update_record(attribute_names = @attributes.keys)
  return super(attribute_names) unless composite?
  
  klass = self.class
  
  attributes_with_values = arel_attributes_with_values_for_update(attribute_names)
  return 0 if attributes_with_values.empty?

  if !can_change_primary_key? and primary_key_changed?
    raise ActiveRecord::CompositeKeyError, "Cannot update primary key values without ActiveModel::Dirty"
  elsif primary_key_changed?
    stmt = klass.unscoped.where(primary_key_was).arel.compile_update(attributes_with_values)
  else
    stmt = klass.unscoped.where(ids_hash).arel.compile_update(attributes_with_values)
  end
  
  klass.connection.update stmt.to_sql
end