Affected Rows for ActiveRecord :: Base.connection.execute

With Rails 4.1.1 using the mysql2 adapter:

I use ActiveRecord connectionto do multiple insertion 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 great, does the job and returns nil.

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

I found the method documentation executesomewhat rare.

+4
source share
2 answers

You can use a method connection.updatethat executes an expression and returns the number of return lines.

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

+7

mysql2. , :

class ActiveRecord::ConnectionAdapters::Mysql2Adapter
  def affected_rows
    @connection.affected_rows
  end
end

ActiveRecord::Base.connection.affected_rows, .

+2

Source: https://habr.com/ru/post/1568189/


All Articles