本文介绍了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

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

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

08-07 07:44