将带有参数的表单提交给新的控制器操作

Submitting a form with a param to new controller action

Rails 6
bootstrap 4

在我的 books_controller.rb 中,我有:

def index
  @books = Book.select(:id, :name)
end

def new
    @book = Book.new
  end

def create
  @book = Book.new(book_params)
  respond_to do |format|
    if @book.save
      format.html { redirect_to @book, notice: 'Book was successfully created.' }
      format.json { render :show, status: :created, location: @book }
    else
      format.html { render :new }
      format.json { render json: @book.errors, status: :unprocessable_entity }
    end
  end
end

我有一个 table,在我的 views/books/index.htmlslim 中,我有:

table.table.table-striped
  thead
    tr
      th Name
  tbody
    - @books.each do |book|
      tr
        td = book.name

我想做的是,在 table 的末尾添加一个表单,允许用户添加一本书,而无需单独的表单,例如:

我试过了:

= form_with url: new_book_path do |f|
  .form-inputs
    = f.label 'Add Book'
    = f.text_field :book_name
  .form-actions
    = f.submit    

我也试过:

= simple_form_for(@book) do |f|
  .form-inputs
    = f.input :book_name

但是没有任何反应,当我点击提交时,我收到以下消息:

ActionController::RoutingError (No route matches [POST] "/bookd/new"):

我也试过:

= simple_form_for(@book || Book.new) do |f|
  .form-inputs
    = f.input :book_name

但是。我得到一个:

ActionView::Template::Error (undefined method `book_name` for #<Book:0x000007f9cce...>);

另一个想法是将其设为 link,类似于:

= link_to new_book_path, :class => "btn btn-primary btn-lg"

但是如何传递 book_name 参数,它应该转到哪个控制器操作?

这是我的路线:

books GET /books(.:format) books#index
POST /books(.:format) books#create
new_book GET /books/new(.:format) books#new
edit_book GET /books/:id/edit(.:format) books#edit
book GET /books/:id(.:format) books#show
PATCH /books/:id(.:format) books#update
PUT /books/:id(.:format) books#update
DELETE /books/:id(.:format) books#destroy

在 Rails 中,您不会通过 post 到 new 路线来创建资源 - 您 post 到收集路线,例如。 /books。新操作仅用于创建一个带有表单的页面。

仍然很费解为什么new_book_path会return /bookd/new 但错误实际上是正确的。 new_book_path 响应 GET - 而不是 POST。 Rails Routing from the Outside.

中对此进行了解释

如果你实际上只是使用:

table.table.table-striped
  thead
    tr
      th Name
  tbody
    - @books.each do |book|
      tr
        td = book.name

= simple_form_for(@book || Book.new) do |f|
  .form-inputs
    = f.input :name # book_name is a typo?

它将正确地创建一个带有 action="/books" method="POST" 的表单。

我不知道你想用这个烂摊子做什么:

= form_with url: new_book_path do |f|
  .form-inputs
    = f.label 'Add Book'
    = f.text_field :book_name
  .form-actions
    = f.submit    

    = simple_form_for(@book) do |f|
      .form-inputs
        = f.input :book_name

但是 the HTML specifications 中的 none 允许嵌套 <form> 元素,结果可能非常难以预测。例如提交按钮可以提交内部表单或外部表单。