Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Affected rows for ActiveRecord::Base.connection.execute

With Rails 4.1.1, using mysql2 adapter:

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
}

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)

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

like image 676
AlexGuti Avatar asked Dec 18 '14 17:12

AlexGuti


2 Answers

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

like image 151
Flexoid Avatar answered Nov 15 '22 22:11

Flexoid


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.

like image 23
pdg137 Avatar answered Nov 15 '22 22:11

pdg137