chand basha
chand basha

Reputation: 51

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.

Upvotes: 5

Views: 1280

Answers (1)

fl00r
fl00r

Reputation: 83680

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/

Upvotes: 5

Related Questions