Ruby on Rails: Multiple Input Fields in The Same F

2019-08-05 13:08发布

问题:

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:

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.