Nested forms regarding polymorphic association

54 Views Asked by At

I have the three classes Book, Nonfiction, Author and I want to make it possible that Book and Author get initialized by calling the Nonfiction's form. But unfortunately, the textfield doesn't show up. If I change the fields_for's parameter :authors to :author then it shows up. Can someone tell me why?

Classes:

class Book < ApplicationRecord
  belongs_to :bookable, polymorphic: true
  has_many :authors
  accepts_nested_attributes_for :authors 
end

class Author < ApplicationRecord
end

class Nonfiction < ApplicationRecord
  has_many :books, as: :book_table
  accepts_nested_attributes_for :books
end

Book's controller

# GET /books/new
  def new
    @book = Book.new
    @book.authors.build
  end
...

  # POST /books or /books.json
  def create
    @bookable = load_book_table
    @book = @bookable.books.new(book_params)

      if @book.save!
        ...
      end
   end
...

 def book_params
      params.require(:book).permit(:book_name, :book_isbn, :book_description, :book_price, authors_attributes: [:author_name])
 end

Nonfiction's View

<%= form_with(model: [@nonfiction, Book.new]) do |form|%>
    <div class="field">
      <%= form.label :book_name %>
      <%= form.text_field :book_name %>
      <br>
      <%= form.fields_for :authors do |author_form| %>
        <%= author_form.label :author_name %>
        <%= author_form.text_field :author_name%>
      <% end %>
      <br>
      <%= form.label :book_isbn %>
      <%= form.text_field :book_isbn %>
      <br>
      <%= form.label :book_description %>
      <%= form.text_field :book_description %>
      <br>
      <%= form.label :book_price %>
      <%= form.text_field :book_price %>
    </div>
    <div class="actions">
      <%= form.submit %>
    </div>
  <% end %>
0

There are 0 best solutions below