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
相关文章