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

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

问题描述

使用 Rails 4.1.1,使用 mysql2 适配器:

With Rails 4.1.1, using mysql2 adapter:

我正在使用 ActiveRecord connection 来执行MySQL 表中的多次插入:

I am using an ActiveRecord connection to execute a multiple insert in a MySQL table:

ActiveRecord::Base.connection.execute %Q{
    INSERT INTO table (`user_id`, `item_id`) 
    SELECT 1, id FROM items WHERE items.condition IS NOT NULL
}

这工作正常,完成工作,并返回 nil.

This works fine, do the job, and returns nil.

有没有办法获取受影响的行数?(避免需要执行另一个查询)

Is there a way to get the number of affected rows? (avoiding the need to execute another query)

我找到了 的文档execute 方法有点稀疏.

I have found the documentation of the execute method somewhat sparse.

推荐答案

您可以使用 connection.update 方法执行表达式并返回受影响的行数.

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 文档 - http://api.rubyonrails.org/v4.2.7/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-update

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

Rails 最新文档 - http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-update

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

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

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