Form item disappearing when failing nested validations
class BooksController < ApplicationController
...def new
@book = Book.new
@book.authors.build
enddef create
@book = current_user.books.create(book_params)
params[:book][:authors_attributes].each do |k,v|
author = Author.find_or_create_by(name: v['name'], user_id: current_user.id)
@book.book_authors.build(author_id: author.id)
endif @book.save redirect_to book_path(@book) else render :new end
end
private
def book_params
params.require(:book).permit(:title, :published_city, :description, author_ids:[])
enddef author_params
params.require(:book).permit(authors_attributes: [:id, :name, :_destroy])
end
end
class Book < ApplicationRecordhas_many :book_authors
has_many :authors, through: :book_authors
belongs_to :useraccepts_nested_attributes_for :authors, allow_destroy: true
validates :title, :published_city, presence: true
validates_associated :authors, inverse_of: :book
end
class BookAuthor < ApplicationRecord
belongs_to :book
belongs_to :author
end
class Author < ApplicationRecord
has_many :book_authors
has_many :books, through: :book_authorsvalidates :name, presence: true
end
<%= form_for @book do |f| %>
<%= f.text_field :title, required: true %>
<%= f.text_area :description %>
<div id='authors'>
<%= f.fields_for :authors do |author| %>
<%= render 'author_fields', :f => author %>
<% end %>
<div class='links'>
<%= link_to_add_association 'Add another author', f, :authors %>
</div>
</div>
<%= f.text_field :published_city %>
<%= f.submit %>
<% end %>
I quickly created a sample app that shows how I use `cocoon` with many-to-many relationships.
It is at https://github.com/dylanpinn/rails-bookstore. Let me know how you go.
Just want to thank you for going to the effort to build this! Love the GoRails community.
However, when I run that code and create a new book, but leave the author field blank, it doesn't seem to be hitting the validation. So I'm able to create a book with no author. Any ideas why this might be?