Ryan McCrary
Ryan McCrary

Reputation: 61

Create multiple records at once ruby on rails

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.

Upvotes: 2

Views: 2479

Answers (1)

EJAg
EJAg

Reputation: 3308

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.

Upvotes: 2

Related Questions