使用Postgres的ActiveRecord :: Base.connection.execute的受影响的行 [英] Affected rows for ActiveRecord::Base.connection.execute with Postgres

查看:122
本文介绍了使用Postgres的ActiveRecord :: Base.connection.execute的受影响的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以使用 ActiveRecord :: Base.connection.execute 来获取SQL操作导致的受影响行数?

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

我找到了此答案用于MySQL适配器,但不适用于Postgres。

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

或者,如果有一种方法可以获取SQL文本响应(例如 UPDATE 126) ,也可以。

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

推荐答案

您可以使用 cmd_tuples 方法:

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

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

这篇关于使用Postgres的ActiveRecord :: Base.connection.execute的受影响的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆