Module: Moribus::Extensions::HasCurrentExtension

Defined in:
lib/moribus/extensions/has_current_extension.rb

Overview

Minor extension for Rails’ has_one association that will help dealing with current record assignment.

Instance Method Summary collapse

Instance Method Details

#remove_target!Object

Sets ‘is_current’ flag of overridden record to false, instead of deleting it or setting foreign key to nil.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/moribus/extensions/has_current_extension.rb', line 8

def remove_target!(*)
  # Use custom update to avoid running ActiveRecord optimistic locking
  # and to avoid updating lock_version column:
  if target.new_record?
    target.is_current = false
    target.updated_at = Time.zone.now if has_updated_at_column?
  else
    klass = target.class

    sql =  "UPDATE #{klass.quoted_table_name} " \
           "SET \"is_current\" = #{klass.connection.quote(false)} "

    sql << %{, "updated_at" = #{klass.connection.quote(Time.zone.now)} } if has_updated_at_column?

    sql << "WHERE #{klass.quoted_primary_key} = " \
           "#{klass.connection.quote(target.send(klass.primary_key))} "

    klass.connection.update sql
  end
end