AlexGuti AlexGuti - 1 year ago 125
MySQL Question

Affected rows for ActiveRecord::Base.connection.execute

With Rails 4.1.1, using mysql2 adapter:

I am using an ActiveRecord

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

This works fine, do the job, and returns

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

I have found the documentation of the
method somewhat sparse.

Answer Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download