Rails 为单个模型插入多条记录 [英] Rails inserting multiple records for single model
本文介绍了Rails 为单个模型插入多条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我应该如何设置表单字段以便能够在数据库中为单个模型插入多行.
How shall I set the form fields to be able to insert multiple rows in the database for a single model.
我正在使用另一个链接更新 div,但无法使用表单助手.所以我需要手动设置字段名称.
I am updating a div with another link and cannot use the form helper. So I need to set the field names manually.
我有一个帖子模型,它有一个标题字段.我想像 post[0][title] 一样将我的帖子插入 db 但是当我像这样命名表单字段时,它会以字符串形式获取 0 并且不记录.
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.
我也尝试从 Rails 控制台设置我自己的数组,如
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.
推荐答案
posts = Array.new
posts << {:title => "title 1"}
posts << {:title => "title 2"}
Post.create(posts)
这篇关于Rails 为单个模型插入多条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文