Create multiple records using single form (Not nested attributes)

倾然丶 夕夏残阳落幕 提交于 2020-02-05 02:36:07

问题


In my application I have a Thought model which has content and author attributes.

I want to create multiple thoughts at once using new form. But this is not a case of nested forms as i am not using any associated models.

Please suggest some solution. Thanks in advance!


回答1:


You can try with the below solution

In your View File

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

Controller Code:

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

Hope it works for you :)




回答2:


In frontend you can use jquery onClick function to add fields for more thoughts ie you can add a link called "add more" & create a jquery function to add fields for another thought in the same form with dynamic field names & in the backend you can use

@thoughts = Thought.create([{ author: 'Chicago', content: 'content' }, { author: 'Chicago', content: 'content' }, .......])

to create multiple entries in one go.



来源:https://stackoverflow.com/questions/27938883/create-multiple-records-using-single-form-not-nested-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!