如何在rails3.0中插入多个记录

时间:2011-10-28 12:29:21

标签: ruby-on-rails

在rails3.0中如何在表中插入多条记录?请告诉我任何示例应用程序。

1 个答案:

答案 0 :(得分:5)

您可以使用交易

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

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

Ot进行一次SQL查询:

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

非常有趣的文章

  

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