3

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!

2 Answers 2

6

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 :)

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

Comments

4

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.

1 Comment

Nice one liner solution!

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.