Search code examples
ruby-on-railsrubynested-formsruby-on-rails-6cocoon-gem

Rails 6 nested form cocoon won't save sub-objects


I am trying to implement a nested form for a Book object which can have several BookAuthor objects. I have followed this tutorial to do this with the Cocoon gem in Rails 6, however it does not work. The form itself works well on the front end, adding and removing the BookAuthor fields properly. The params that the server receives contain the correct number of BookAuthor attributes but these sub-objects do not get written to the database, even though the main Book object does. I have been able to get the association to work properly.

There is no error output from either the javascript or rails consoles.

Notes: Ignore the include Hashid::Rails in book.rb, I have tried both with and without this and the same thing occurs. Also, ignore any references to Chapter objects in book.rb, as these are not part of the form yet.

Below is the code for the relevant models, views and controllers. The model files also contain the table schema for that model. If there is any more code you require, please let me know.

Params the server receives (from the server console): https://pastebin.com/nxAXkD3T

book.rb: https://pastebin.com/Xtxf52eT

book_author.rb: https://pastebin.com/miFhb5wR

_form.html.haml: https://pastebin.com/YaW1gRUe

_book_author_fields.haml: https://pastebin.com/FJw7CR2f

books_controller.rb: https://pastebin.com/0NYsCc7x

application.js: https://pastebin.com/rZLpe0iS

Gemfile: https://pastebin.com/TcGrQ9f5

Gemfile.lock: https://pastebin.com/apCMxNkJ

package.json: https://pastebin.com/9U7mB2NK

yarn.lock: https://pastebin.com/H3AzG3Bi


Solution

  • There is no need to add the attr_accessor :book_authors_attributes. in your book.rb. remove it.

    This is automatically added with some rails magic.