使用单个表单创建多个记录(非嵌套属性)

Ash*_*rma 3 forms ruby-on-rails ruby-on-rails-4

在我的应用程序中,我有一个具有内容和作者属性的思想模型。

我想使用新形式一次创建多个想法。但这不是嵌套表单的情况,因为我没有使用任何关联的模型。

请提出一些解决方案。提前致谢!

Nik*_*ria 5

您可以尝试使用以下解决方案

在您的查看文件中

<%= form_tag your_action_path do %>
  <% 4.times do |i|%>
    Content : <%= text_area_tag :thought_content, "", :name => "thoughts[][content]" %>
    Author : <%= text_field_tag :thought_author, "", :name => "thoughts[][author]" %>
  <% end %>
  <%= submit_tag "Submit" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

控制器代码:

def your_action
  params[:thoughts].each do |thought_params|
    Thought.create(thought_params)
  end
  ###
  #Any further code#
  ###
end
Run Code Online (Sandbox Code Playgroud)

希望这对你有用 :)