Module: IncrementWithSql
- Defined in:
- lib/increment_with_sql.rb,
lib/increment_with_sql/version.rb
Defined Under Namespace
Classes: InvalidAttributeError, NotPersistedError
Constant Summary
collapse
- VERSION =
"0.0.1"
Instance Method Summary
collapse
Instance Method Details
#decrement_with_sql!(attribute, by = 1) ⇒ Object
28
29
30
|
# File 'lib/increment_with_sql.rb', line 28
def decrement_with_sql!(attribute, by = 1)
increment_with_sql! attribute, by * -1
end
|
#increment_with_sql!(attribute, by = 1) ⇒ Object
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
# File 'lib/increment_with_sql.rb', line 9
def increment_with_sql!(attribute, by = 1)
raise(NotPersistedError, "Record not persisted") if new_record?
raise(InvalidAttributeError, "Invalid attribute #{attribute}") unless attribute_names.include?(attribute.to_s)
self.class.transaction do
self.class.where(:id => id).update_all("#{self.class.connection.quote_column_name attribute} = CASE WHEN #{self.class.connection.quote_column_name attribute} IS NULL THEN 0 ELSE #{self.class.connection.quote_column_name attribute} END + #{by.to_i}")
send "#{attribute}=", self.class.where(:id => id).select(attribute).first.send(attribute)
if respond_to?(:clear_attribute_changes, true)
send :clear_attribute_changes, attribute
else
changed_attributes.except! attribute.to_s
end
end
self
end
|