问题
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