Rails inserting multiple records for single model

旧巷老猫 提交于 2019-12-02 04:46:16

问题


How shall I set the form fields to be able to insert multiple rows in the database for a single model.

I am updating a div with another link and cannot use the form helper. So I need to set the field names manually.

I have a post model and it has a title field. I want to insert i posts to db like post[0][title] But when I name the form field like this It gets 0 as string and does not record.

Also I tried to set the Array my self from Rails Console like

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

And still nothing is saved.


回答1:


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



回答2:


is this what you're trying to do?

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

posts.each do |post|
  post.save
end


来源:https://stackoverflow.com/questions/4495705/rails-inserting-multiple-records-for-single-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!