Last active
October 30, 2018 12:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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