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.

new_step_4_html.erb

<%= form_for(@post) do |f| %>
  <%= f.text_field :content %>
  <%= f.text_field :content %>
  <%= f.text_field :content %>
<% end %>

projects_controller.rb

def new_step_4
  @post = Post.new
end

Right now, all it does is submit one :content field, obviously because they all share the same id/value. Unfortunately, the Railscasts #197 applies for nested forms, so the javascript and helper stuff he does all applies for nested. I would think this is something simple. Person from IRC mentioned I could do some sort of '3.times' code into the view file or something?

1 Answer 1

4

First of all you will probably have to edit the model of you post.

post.rb

has_many :contents, :dependent => :destroy
accepts_nested_attributes_for :contents

You will need another model to store the content fields. so first generate a model

rails g model content post_id:integer body:text

the model

content.rb

belongs_to  :post

Now, in stead of doing <%= f.text_field :content %> a few times, let rails create them, because now you basically let them overwrite each other.

3.times do
  content = @post.content.build
end

the form view will be something like this:

<%= form_for @post do |f| %>
  <%= f.fields_for :contents do |builder| %>
    <%= builder.label :body, "Question" %><br />
    <%= builder.text_area :body, :rows => 3 %><br /> 
  <%= end %>     
  <p><%= f.submit "Submit" %></p>
<% end %>

I did not test this code, but the idea should be correct. Let me know if you need more info.

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

3 Comments

Hey Rik, thanks for your answer. Currently the 'content' is a column in my Post table. so for Post, I have content, user_id, project_id. So it won't be a nested form.
but then you can not have multiple content fields, as your table only has space for one.
Oh, I see. Thank you rik for trying to help me out.

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.