Skip to content

Instantly share code, notes, and snippets.

@ta
Last active October 30, 2018 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ta/663969 to your computer and use it in GitHub Desktop.
Save ta/663969 to your computer and use it in GitHub Desktop.
Add Postgresql RETURNING <column> to ActiveRecord when updating more than a single row
# USAGE:
#
# class SomeModel < ActiveRecord::Base
# include ActiveRecord::PostgresqlExtensions
# end
#
# SomeModel.update_all_returning("count = count + 1", nil, ["id", "count"])
#
module ActiveRecord
module PostgresqlExtensions
def self.included base
base.send :extend, ClassMethods
end
module ClassMethods
def update_all_returning(updates, conditions = nil, returning_columns = [])
raise ActiveRecord::ActiveRecordError, "Adapter is not PostgreSQL" unless connection.adapter_name == 'PostgreSQL'
raise TypeError, "can't convert #{returning_columns.class} into Array" unless returning_columns.class == Array
returning_columns = returning_columns.map{ |x| connection.quote_string(x) }
sql = "UPDATE #{quoted_table_name} SET #{sanitize_sql_for_assignment(updates)} "
sql << "WHERE " << sanitize_sql_for_conditions(conditions)
sql << " RETURNING #{returning_columns.join(', ')}" if returning_columns.length > 0
res = connection.execute(sql, "#{name} Update")
connection.result_as_array(res)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment