2

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 %>
2
  • 1
    You want to create 3 unique posts out of one form? Commented Dec 19, 2011 at 4:28
  • 1
    chief - Yes, I think so. or should I create a new form for each? and display 3 forms on the same view page? Commented Dec 19, 2011 at 5:14

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I followed your suggestion for what I'm doing how can I display the views in my show.html. My show.html doesn't recognized 'content_array[]'
show me the code you have tried and the error message you got (edit your answer above and put it there).
A small correction. The browser does post all the different fields. However the rails params parser will use the value of the last name. You can check this by inspecting the request.body in your rails code.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.