嵌套验证失败时表单项消失

时间:2018-06-12 11:34:40

标签: ruby-on-rails activerecord cocoon-gem

我有一个Rails 5应用程序,我在使用带有嵌套动态表单的Cocoon gem进行验证时遇到问题。

当我的Book模型上的验证失败,而我的create操作呈现:new时,Author字段会从我的新图书表单中消失。

我注意到的一件事是,当验证失败时,而不是将authors传回我的表单,由于我book_authors中的行@book.book_authors.build(author_id: author.id),它正在传递create 1}}行动。很确定这是我的问题的原因,但不知道如何解决它。

books_controller.rb

class BooksController < ApplicationController
  ...

  def new
    @book = Book.new
    @book.authors.build
  end

  def 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)
    end

    if @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:[])
  end

  def author_params
    params.require(:book).permit(authors_attributes: [:id, :name, :_destroy])
  end
end

book.rb

class Book < ApplicationRecord

  has_many :book_authors
  has_many :authors, through: :book_authors
  belongs_to :user

  accepts_nested_attributes_for :authors, allow_destroy: true
  validates :title, :published_city, presence: true
  validates_associated :authors, inverse_of: :book
end

book_author.rb

class BookAuthor < ApplicationRecord
  belongs_to :book
  belongs_to :author
end

author.rb

class Author < ApplicationRecord
  has_many :book_authors
  has_many :books, through: :book_authors

  validates :name, presence: true
end

new.html.erb

<%= 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 %>

0 个答案:

没有答案