Affected rows for ActiveRecord::Base.connection.execute

徘徊边缘 提交于 2019-12-05 08:49:25

You can use connection.update method which executes expression and returns affected rows count.

ActiveRecord::Base.connection
  .update("INSERT INTO accounts (`name`) VALUES ('first'), ('second')")

=> 2

Rails v4.2.7 doc - http://api.rubyonrails.org/v4.2.7/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-update

Rails latest doc - http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-update

Here is an easy way to get the number of affected rows using the mysql2 adapter. Put this in a file that gets loaded by your app:

class ActiveRecord::ConnectionAdapters::Mysql2Adapter
  def affected_rows
    @connection.affected_rows
  end
end

Then you will be able to run ActiveRecord::Base.connection.affected_rows to get the number of affected rows.

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