Rails为单个模型插入多个记录

时间:2010-12-21 01:59:10

标签: ruby-on-rails model insert records

如何设置表单字段,以便能够在数据库中为单个模型插入多行。

我正在使用其他链接更新div,并且无法使用表单助手。所以我需要手动设置字段名称。

我有一个帖子模型,它有一个标题字段。   我想将post发布到db,如post [0] [title]但是当我将表单字段命名为this时,它将0作为字符串并且不记录。

此外,我尝试从Rails控制台设置我自己的数组,如

post = Array.new
post << [:title => "title 1"]
post << [:title => "title 2"]
sav = Post.new(post)
sav.save 

仍然没有任何东西被保存。

2 个答案:

答案 0 :(得分:7)

posts = Array.new
posts << {:title => "title 1"}
posts << {:title => "title 2"}
Post.create(posts)

答案 1 :(得分:5)

这是你想要做的吗?

posts = []
posts << Post.new(:title => "title 1")
posts << Post.new(:title => "title 2")

posts.each do |post|
  post.save
end