2

This seemed fairly straightforward, but is proving not to be.

I have two models: Authors and Books. Authors has_many books, books belong_to authors. I'd like to be able to add many books in a single form with different authors and information for each.

class BooksController < ApplicationController

def new
 @books = []
  5.times do
    @books << Book.new
  end
end

I'm not sure if that's the correct way to form the controller. The view is as follows:

<%= form_tag(books_path(@books)) %>
 <% @books.each do |book| %>
  <%= text_field_tag(:title) %>
  <%= text_field_tag(:author) %>
  <%= text_field_tag(:pages) %>
 <% end %>
<%= submit_tag("Submit") %> 

That's as far as I've gotten, as I can't get the @books to end up in my params, so I haven't gotten to trying the create method yet. All i'm getting is the :title, :author and :pages of the last record, and they aren't even in a book param.

1
  • You're after the fields_for helper. Commented Sep 11, 2017 at 21:36

1 Answer 1

2

form_tag doesn't know your model object. So it won't wrap your params under the appropriate key. You should instead use form_for to save yourself the trouble of constructing the params.

In order to create associated objects you can use accepts_nested_attributes_for.

In order to create multiple objects you need to send their params to your controller in an array. But I'd suggest you save single record only. You code would be cleaner and you can take advantage of Rails form helpers such as form_for and fields_for instead of constructing the HTML code by hand.

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

3 Comments

What would be the proper way to construct with form_for? The @books local variable is an array, so I'm not sure how it works with that method
If you want to stick with @books and creating multiple records in one form, you'll probably be stuck with form_tag and constructing HTML manually, like the linked solution. But I think it's better to create one record in one form. The code is cleaner, and the user experience is probably better. You can always use ajax if you want to allow users to continue creating records without being redirected.
Yea, the goal was to create multiple records with one form to make it quicker. The app already has a form for adding one, but wanted to explore adding a form that allows for a bulk-style import.

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.