Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Affected rows for ActiveRecord::Base.connection.execute with Postgres

Is there a way to get the number of affected rows resulting from a SQL operation using ActiveRecord::Base.connection.execute?

I found this answer for MySQL adapters, but it doesn't work with Postgres.

Alternatively, if there's a way to get the SQL text response (e.g. "UPDATE 126"), that would work too.

like image 492
Yarin Avatar asked Sep 17 '25 08:09

Yarin


1 Answers

You can use cmd_tuples method:

sql = "UPDATE users SET updated_at = '#{DateTime.now}' WHERE id = 1"
ActiveRecord::Base.connection.execute(sql).cmd_tuples
# => 1

Documentation: http://www.rubydoc.info/gems/pg/0.17.1/PG%2FResult:cmd_tuples

like image 184
MrYoshiji Avatar answered Sep 19 '25 03:09

MrYoshiji