1

I'm working on a dynamic form in a Rails app, and I need to insert a variable number of records into a model in a single form submission. I've done this using PHP -> MySQL/Postgres before, but I have no idea how to do it in Rails.

Ultimately, users should be able to create any number of records to be inserted, but in my example below, I'm limiting it to 2... let me see if I can do that, first...

Here's the form - the ids all get a unique suffix because they are being populated dynamically from localStorage objects on submission.

new.html.erb

<%= form_for @entry, html: {id: :new_entry_form} do |f| %>
    <% for i in 0..1 %>
        <%= f.text_field :name, :id => 'name_#{i}' %>
        <%= f.text_field :day, :id => 'day_#{i}' %>
    <% end %>
<% end %>

Here's the associated controller - I'm sure that this is missing something, but I don't know what.

def new
    @entry = Entry.new
end

def create
    @entry = Entry.create(entry_params)
    redirect_to "http://localhost:3000/entries"
end

private
def entry_params
    params.require(:entry).permit(:name, :day)
end

Any help would be much appreciated.

3
  • 'name'"_#{i}"'' can simply be written as "name_#{i}" -- FYI Commented May 26, 2016 at 0:45
  • You're correct, but in this case, it needed to be written that way- the form is actually appended to the body via jQuery, so it lives inside of a JavaScript variable as a string - hence the need for the extra quote situation. I wrote it in typical Ruby format here for simplicity, but didn't think to change the attribute formatting. Commented May 26, 2016 at 1:46
  • But hey, any thoughts on my question? Commented May 26, 2016 at 1:47

1 Answer 1

0

Follow this link it shows how to create multiple object in one form submit:

http://vicfriedman.github.io/blog/2015/07/18/create-multiple-objects-from-single-form-in-rails/

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

2 Comments

THANK you. I was having such a hard time finding resources about how to do this - I guess people don't have to do this very often? I feel like it has come up in several projects that I've worked on, this is just the first time for me in a Rails app.
Please add the relevant code here, that link is broken.

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.