Ruby on Rails: Multiple Same Input Fields in Same Form

末鹿安然 提交于 2019-12-07 20:18:06

问题


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 %>

回答1:


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.



来源:https://stackoverflow.com/questions/8556888/ruby-on-rails-multiple-same-input-fields-in-same-form

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