简体   繁体   中英

Ruby on Rails: Multiple Same Input Fields in Same Form

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

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.

What you can do is convert to html and as an array in your form:

<input`type="text" name="post[content][]" id="content_id">

Then, in your controller:

content_details = params[:post][:content]
content_details.each do|cont|
@post = Post.new(content: cont)
@post.save

This will loop through all of the content created and save each.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM