Notes posted by timdorr
RSS feed
timdorr -
April 4, 2013 - (>= v1.0.0)
0 thanks
increment_by_sql for PG
Note, if you’re using the code below for incrementing by SQL with a Postgres database, it’s not going to like the backticks. Just remove them:
def increment_with_sql!(attribute, by = 1) raise ArgumentError("Invalid attribute: #{attribute}") unless attribute_names.include?(attribute.to_s) original_value_sql = "CASE WHEN #{attribute} IS NULL THEN 0 ELSE #{attribute} END" self.class.update_all("#{attribute} = #{original_value_sql} + #{by.to_i}", "id = #{id}") reload end