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

发布于 2024-10-08 05:57:23 字数 397 浏览 0 评论 0原文

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

我正在使用另一个链接更新 div,但无法使用表单助手。所以我需要手动设置字段名称。

我有一个帖子模型,它有一个标题字段。 我想像 post[0][title] 一样将 i posts 插入到数据库但是当我像这样命名表单字段时它会得到 0 作为字符串并且不会记录。

我还尝试从 Rails Console 中自行设置数组

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

,但仍然没有保存任何内容。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苍景流年 2024-10-15 05:57:23
posts = Array.new
posts << {:title => "title 1"}
posts << {:title => "title 2"}
Post.create(posts)
posts = Array.new
posts << {:title => "title 1"}
posts << {:title => "title 2"}
Post.create(posts)
彩虹直至黑白 2024-10-15 05:57:23

这就是你想做的吗?

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

posts.each do |post|
  post.save
end

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文