alex_the_emperor
alex_the_emperor

Reputation: 99

Rails 5.1.4 fields_for for multiple objects

I have an Author and Book model. An Author can have many Book, but a Book can only have one Author.

During the creation of a new Author, how do I add a "New Book" button which will add a fields_for for the Author form? I want to be able to add more than one Book. So far, the solution that I have found is just to add a fixed number of fields_for, like this:

<%= form_with(model: author, local: true) do |form| %>
...
    <% 5.times do %>
        <%= form.fields_for :books do |books| %>
        ...
        <% end %>
    <% end %>
...
<% end %>

I do not want it to be like this, what if the author has more than 5 books? I want to be able to add books dynamically. Any solutions?

Upvotes: 1

Views: 84

Answers (2)

Vishal
Vishal

Reputation: 7361

author.rb

accepts_nested_attributes_for :books,
    :allow_destroy => true,
    :reject_if     => :all_blank

In your view file

<div class="bank_account_details">
  <%= f.fields_for :bank_account_details do |builder| %>
    <p>
    Book: <%= builder.text_field :name %>
          <%= builder.check_box :_destroy %>
          <%= builder.label :_destroy, "Remove Book" %>
    </p>
  <% end %>
<div>
<%= link_to_add_fields "Add Book", f ,:books %>

In your controller add parameters

params.require(:author).permit(:name, books_attributes: [:id, :name, :_destroy])

Upvotes: 1

Igor Drozdov
Igor Drozdov

Reputation: 15045

If you fine with adding a new dependency, there's cacoon gem, which allows you easier handle nested forms.

It's an additional dependency, but the code for adding a new associated record is simple as:

<%= form_for author do |f| %>
  ...
  <%= f.fields_for :books do |book| %>
    <%= render 'book_fields', f: book %>
    <%= link_to_add_association 'add book', f, :books %>
  <%end%>

Upvotes: 3

Related Questions