Ruby on Rails:同一表单中的多个输入字段 - 更改 ID/值

Ruby on Rails:同一表单中的多个输入字段 - 更改 ID/值

问题描述:

有一个页面,其中有多个相同内容的输入字段,帖子.现在,当用户输入问题时,假设有 3 个字段,唯一保存到数据库的字段是最后一个.然而,它应该保存所有三个并给他们每个人自己的 post_id.还;如果用户没有为其他字段输入任何内容,它也不应该保存在数据库中.

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

现在,它所做的只是提交一个 :content 字段,显然是因为它们共享相同的 id/value.不幸的是,Railscasts #197 适用于嵌套表单,因此他所做的 javascript 和帮助程序都适用于嵌套.我认为这很简单.来自 IRC 的人提到我可以在视图文件中添加某种3.times"代码?

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?

首先,您可能需要编辑帖子的模型.

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

模型

content.rb

belongs_to  :post

现在,与其做几次 <%= f.text_field :content %> ,不如让 rails 创建它们,因为现在你基本上让它们相互覆盖了.

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

表单视图将是这样的:

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