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

倖福魔咒の 提交于 2019-12-24 00:46:35

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/45676860/affected-rows-for-activerecordbase-connection-execute-with-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!