Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert multiple records in rails3.0

In rails3.0 how to insert multiple records in a table? plz tell me any example application.

like image 579
chand basha Avatar asked Oct 28 '11 12:10

chand basha


1 Answers

You can use transactions

titles = ["T-Shirt", "Boots", "Cap"]

ActiveRecord::Base.transaction do
  titles.each do |title|
    Thing.create(:title => title)
  end
end

Ot make one sql query:

query = []
titles.each do |title|
  query << "('#{title}')"
end
sql = "INSERT INTO things ('title') VALUES #{query.join(", ")}"
ActiveRecord::Base.connection.execute(sql)

Quite interesting article

http://www.coffeepowered.net/2009/01/23/mass-inserting-data-in-rails-without-killing-your-performance/

like image 168
fl00r Avatar answered Sep 24 '22 18:09

fl00r