Ruby on Rails:相同形式的多个相同输入字段 [英] Ruby on Rails: Multiple Same Input Fields in Same Form
问题描述
有一个页面,其中有多个相同内容的输入字段,帖子.现在,当用户输入问题时,假设有 3 个字段,唯一保存到数据库的字段是最后一个.然而,它应该保存所有三个并给他们每个人自己的 post_id.还;如果用户没有为其他字段输入任何内容,它也不应该保存在数据库中.
Have a page where there are multiple input fields of the same thing, Posts. Right now, when a user enters in a question for, let's say 3 fields, the only one that saves to the database is the last one. Whereas, it should save all three and give them each it's own post_id. Also; if the user doesn't enter anything in for the other fields, it should not save in the database either.
<%= form_for(@post) do |f| %>
<%= f.text_field :content %>
<%= f.text_field :content %>
<%= f.text_field :content %>
<% end %>
推荐答案
它失败了,因为你上面得到的评估结果为具有 same name/id 的 html 字段,并且浏览器只会发布其中之一的价值.如果它们是不同的字段,那么您需要为它们提供唯一的名称/ID 或者您需要将它们创建为一个数组,例如:
It's failing because what you've got above evaluates to thee html field with the same name/id and the browser will only post the value for one of them. If they are different fields, then you need to give them unique names/ids or you need to create them as an array eg:
<%= f.text_field_tag 'content_array[]' %>
或者,如果您希望这些成为一组帖子 - 您需要使用自定义表单添加多个子表单(每个帖子一个).
or, if you want these to be a set of posts - you'll need to add multiple sub-forms (one for each post) using a custom form.
这篇关于Ruby on Rails:相同形式的多个相同输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!